VUE:vue源码--v-model双向绑定原理(五颗星)

注意:

1.vue源码--v-model双向绑定原理

双向绑定原理:通过Obje.defineProperty劫持数据发生的改变,如果数据发生改变了(在set中进行赋值的),触发update方法进行更细节点内容({{str}}),从而实现数据双向绑定的原理

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写vue添加事件</title>
</head>

<body>
    <div id="app">
        <h1>{{ str }}</h1>
        {{str}}
        <p>{{a}}</p>
        <button @click="btn">按钮</button>
        <input type="text" name="" v-model="str">
    </div>
    <script type="text/javascript" src="newvue.js"></script>
    <!-- <script type="text/javascript" src="vue.js"></script> -->
    <script type="text/javascript">
        new Vue({
            el: '#app',
            data: {
                str: 'str',
                a: "a"
            },
            beforeCreate() {
                console.log('beforeCreate', this.$el, this.$data)
            },
            created() {
                console.log('created', this.$el, this.$data)
            },
            beforeMount() {
                console.log('beforeMount', this.$el, this.$data)
            },
            mounted() {
                console.log('mounted', this.$el, this.$data)
            },
            methods: {
                btn(e){
                    this.str="str改变了"
                    console.log(this.str)
                    
                }
            }
        }) 
    </script>
</body>

</html>

newvue.js:

// newvue.js
class Vue{
    constructor(options){
        this.$options=options
        this.$watchEvent={}
        // 2.生命周期
        if(typeof options.beforeCreate=="function"){
            options.beforeCreate.apply(this)
        }
        // data
        this.$data=options.data
        this.proxyData()
        this.observe()
        if(typeof options.created=="function"){
            options.created.apply(this)
        }
        if(typeof options.beforeMount=="function"){
            options.beforeMount.apply(this)
        }
        // 节点
        this.$el=document.querySelector(options.el)
         // 模板解析
         this.compileTemplate(this.$el)
        if(typeof options.mounted=="function"){
            options.mounted.apply(this)
        }
    }
    // 4.数据劫持
    // 给Vue大对象赋属性,来

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

前端面试题 文章被收录于专栏

前端面试的一些常问问题、问题的具体实现(可直接运行)以及底层原理

全部评论

相关推荐

06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
05-29 22:11
门头沟学院 Java
Elastic90:抛开学历造假不谈,这公司的招聘需求也挺怪的,Java开发还要求你有图文识别、移动端开发和c++的经验,有点逆天了。
点赞 评论 收藏
分享
评论
1
4
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务