vue动态绑定原理

参考网址:
1.https://www.jianshu.com/p/f194619f6f26?from=singlemessage&isappinstalled=0
2.http://www.cnblogs.com/kidney/p/6052935.html

四大步骤

==1.监听器Observer==:用来劫持监听所有的属性,主要运用Object.Proprety属性来监听数据。如果有改变时,就通知订阅器,由订阅器来通知所有的订阅者。

==2.订阅器Dep==: 用来管理所有的订阅者,主要是一个数组,保存所有的订阅者

==3.订阅者Watcher==: 每一个watcher都有一个更新函数Update,当接收到订阅器的通知改变时,就会执行update函数,从而更新视图

==4.解析器Compile==: 扫描和解析每个节点的相关指令(v-model, v-on等v-指令),如果存在v-model,v-on等指令,解析器compile就会初始化这些模板数据,使之可以页面首次打开时把vue实例的数据显示在视图上,然后初始化相应的订阅者Wather

完整流程

下面代码的实现流程:
可以从这个Vue函数开始入手

        function Vue(options){
            console.log(this); //this是指向实例对象
            this.data = options.data;
            var data = this.data;
            observe(data,this);  //第一步
            var id = options.el;
            var dom = nodeToFragment(document.getElementById(id),this); //第二部
            document.getElementById(id).appendChild(dom);
        }
        var vm = new Vue({
            el: 'app',
            data:{
                text:'hello world'
            }
        })

第一步:创建一个observe去监听vue的实例vm中data的所有属性

第二步:调用nodeToFragment()
①==劫持==id=‘app’的元素下的所有子节点。(后面对于DOM的操作都在这里进行操作,最后更新完成再更新到我们真正的DOM树上,避免对DOM的反复操作)
②在这里调用解析器compile

第三步:compile()
①遍历dom中节点是否有v指令属性,有的话就对视图进行==初始化==(如:把上面的text:‘hello world’初始化到<input type="text" v-model="text">value中)
②为所有有v指令的节点==创建一个watcher==,并把对应的动态绑定属性值传过去
compile中与Observer的联系:
③在初始化的过程中,就必定会调用到我们observe的get方法,因此==在Observe这里把watcher添加到订阅器Dep中==
④在compile中我们还会设置对事件的监听(如input事件),执行了对视图中的数据修改->反映到model数据中(调用observer的set方法)

第四步:Observer通知订阅器Dep,数据值已修改。Dep.notify()通知所有的watcher去更新视图

动态绑定测试代码

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
     <div id="app">
        <input type="text" v-model="text">
        {{ text }}
    </div>

    <script type="text/javascript">


        //监视者
        /**
         * [observe description]
         * @param  {[type]} obj [vue的data]
         * @param  {[type]} vm  [vue实例]
         * @return {[type]}     [description]
         */
        function observe(obj,vm){
             Object.keys(obj).forEach(function (key) {
                defineReactive(vm, key, obj[key]);
             })
        };

        /**
         * [defineReactive description]
         * @param  {[type]} obj [vue实例]
         * @param  {[type]} key [属性名]
         * @param  {[type]} val [属性值]
         * @return {[type]}     [description]
         */
        function defineReactive(obj, key, val){
            console.log('observe:defineReactive');
            var dep = new Dep();
            console.log(dep);
            //obj:vue实例vm(被操作的目标对象),key要定义or要修改的属性名
            Object.defineProperty(obj,key,{
                get : function (){
                    console.log('gettttttttt!');
                    console.log(Dep.target);
                    if(Dep.target)
                        dep.addSub(Dep.target)
                    return val;
                },
                set : function (newVal){
                    console.log('set!!!!!!!!!!!!!!!!');
                    if(newVal === val) return;
                    val = newVal;
                    console.log(val);
                    dep.notify();
                }
            });
        };

        //解析器
        //node:劫持的dom, vm:vue实例
        function compile (node, vm) {
            console.log('compile-----start');
            var reg = /\{\{(.*)\}\}/;
            if(node.nodeType === 1)  //元素,查找v-modal绑定的属性值
            {
                var attr = node.attributes;
                for(var i=0;i<attr.length;i++){
                    if(attr[i].nodeName == 'v-model'){
                        var name = attr[i].nodeValue; //v-model的属性名
                        node.addEventListener('input',function(e){
                            console.log('检测到值改变:'+e.target.value);
                            vm[name] = e.target.value; //给相应的 data 属性赋值,进而触发该属性的 set 方法
                        });
                        node.value = vm[name];  //把vue对应属性名的值赋给节点,触发get方法,vm.data[name]不会触发get方法,但是vm[name]会触发get方法!!
                        node.removeAttribute('v-model');  //为什么要删除v-model?
                    }
                }
                new Watcher(vm, node, name, 'input'); //通知watcher去修改?
            }
            if(node.nodeType === 3){
                 if (reg.test(node.nodeValue)) {
                  var name = RegExp.$1; // 获取匹配到的字符串
                  name = name.trim();

                  new Watcher(vm, node, name, 'text');
                }
            }
            console.log('compile-----end');
        }

        //订阅器
        function Dep (){
            this.subs = [];
            console.log('dep');
        }

        Dep.prototype =  {
            addSub: function(sub){
                console.log('addToDep')
                this.subs.push(sub);
            },
            notify: function(){
                this.subs.forEach(function(sub){
                    sub.update();  //通知watch去update
                });
            }

        }
        
        
        //var vdom = nodeToFragment(document.getElementById('app'));
        //console.log(vdom);

        function nodeToFragment(node,vm){
            console.log('nodeToFragment---start');
            var flag = document.createDocumentFragment();
            var child;
            //console.log(node.childNodes); // length : 5
            while (child = node.firstChild){
                compile(child,vm); //把劫持的child给compile解析
                flag.appendChild(child);
            }
            //console.log(node.childNodes);  // length : 0 
            console.log('nodeToFragment------end')
            return flag;
        }


    /**
     * [Watcher 订阅者]
     * @param {[type]} vm       [vue实例对象]
     * @param {[type]} node     [含有v指令的节点]
     * @param {[type]} name     [description]
     * @param {[type]} nodeType [description]
     */
    function Watcher (vm, node, name, nodeType) {
      console.log('watcher');
      console.log(this);
      //Dep target是Dep和watcher关联的唯一桥梁
      Dep.target = this;
      /**
       * 关于Dep.target: 是一个全局变量,保存了当前的watcher
       * wathcer构造函数中,为Dep.target赋值后会通过watcher.update()方法去调用observe.get()
       * 在observer.get()方法中就是根据Dep.target来把当前watcher加入到订阅器Dep中
       * 所以在把wathcer加入完Dep后,Dep.target就没有用了,所以在this.update()后面要把Dep.watcher设为null
       */
      this.name = name;
      this.node = node;
      this.vm = vm;
      this.nodeType = nodeType;
      this.update();
      Dep.target = null;
    }

    Watcher.prototype = {
      //更新视图上的值,{{ value }}
      update: function () {
        this.get();
        if (this.nodeType == 'text') {
          this.node.nodeValue = this.value;
        }
        if (this.nodeType == 'input') {
          this.node.value = this.value;
        }
      },
      // 获取 data 中的属性值
      get: function () {
        this.value = this.vm[this.name]; // 触发相应属性的 get
      }
    }

        function Vue(options){
            console.log(this); //this是指向实例对象
            this.data = options.data;
            var data = this.data;
            observe(data,this);
            var id = options.el;
            var dom = nodeToFragment(document.getElementById(id),this);
            document.getElementById(id).appendChild(dom);
        }

        var vm = new Vue({
            el: 'app',
            data:{
                text:'hello world'
            }
        })
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • vue理解浅谈 一 理解vue的核心理念 使用vue会让人感到身心愉悦,它同时具备angular和react的优点...
    ndxs2008阅读 24,365评论 2 18
  • 我的github: vue双向绑定原理 MVC模式 以往的MVC模式是单向绑定,即Model绑定到View,当我们...
    KlausXu阅读 45,397评论 7 90
  • 再次看了上次写的博客关于Vue的MVVM,发现虽然介绍了MVVM的原理,但是感觉还不够详细,现在就再次根据这篇博客...
    大春春阅读 2,004评论 0 5
  • “推磨,摇磨/推粑粑,请噶噶(外婆)/推豆腐,请舅母/舅母不吃菜豆腐/要吃隔壁的老鸡母/炖又炖不耙(软),煮又煮不...
    渝夫2016阅读 1,345评论 0 2
  • 什么是丧文化? 举几个例子感受一下。 2016年的夏天,以葛优躺为先锋的一场比废大战拉开了序幕。在“葛优瘫躺”的带...
    爱学习的小王子阅读 3,979评论 0 4

友情链接更多精彩内容