美文网首页
简单手写小白氏理解vue双向绑定原理

简单手写小白氏理解vue双向绑定原理

作者: 最x程序猿 | 来源:发表于2021-04-08 20:53 被阅读0次
image.png

一个input,一个按钮,一个显示值,把大象装冰箱,总共分三步:
(1) 一个input,用v-model指令实现双向数据绑定(1.改变number数据,template input框值跟着变。2.input框值改变,number数据变)
(2) 一个button,用v-on:click 实现绑定事件(解析指令,绑定click监听事件)
(3) 一个h3,用v-bind和 {{ }} 实现动态数据监听(引用number的template都跟着改变)

<html>
    <div id="app">
      <form>
        <input type="text" v-model="number">
        <button type="button" v-on:click="increment">增加</button>
      </form>
      <h3 v-bind:title="number">{{number}}</h3>
    </div>
    <script>
      // 我理解当存储容器了 key是data的每个属性, value是_directives数组
      // 放着 complie dom后的依赖属性的每个节点信息, 用来监听set属性值改变后, 更新dom节点值
      var _binding = {};
      this.init();

      // 初始化
      function init() {
        // data
        this.obj = {
          number: 0
        };
        this.observe();
        this.complie(document.querySelector("#app"));
      };

      /*
       * _observe方法劫持data对象里的属性, 每个属性重写set方法, 这个属性值改变时候触发set方法,
       *  去_binding里找这个属性key,更新complie时订阅的dom节点值
       */
      function observe() {
        _this = this;
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            console.log(this._binding)
            this._binding[key]= {
            _directives : []
          }
          value = obj[key];
          // 劫持get、set方法
          Object.defineProperty(obj, key, {
            get: function () {
              console.log('get被调用');
              return value;
            },
            set: function (newValue) {
              console.log('set被调用,newValue:' + newValue);
              value = newValue;
              // 通知订阅者 改变节点
              console.log(_this._binding);
              if (_this._binding[key]) {
                _this._binding[key]._directives.forEach(dir => {
                  [dir.el][0][dir.attr] = value;
                });
              }
            }
          })
        }

      };
    }

      /**
       * complie解析模板DOM指令 放入_binding 订阅依赖
       * (就是哪块dom依赖哪个值,key value 形式存进放入_binding{}里)
       */
      function complie(root) {
        let _this = this;
        let nodes = root.children;
        console.log(nodes);
        for (let index = 0; index < nodes.length; index++) {
          const element = nodes[index];
          console.log(element)
          if (element.children.length) {
            this.complie(element);
          }

          // 解析v-on:click
          if (element.hasAttribute('v-on:click')) {
            console.log('hasAttribute:v-on:click')
            element.addEventListener('click', function () {
              console.log('click');
              _this.increment();
            }, false)
          }

          // 解析v-model
          if (element.hasAttribute('v-model')) {
            console.log('hasAttribute:v-model');
            let attrVal = element.getAttribute('v-model');
            // 监听input框输入值时 改变属性值
            element.addEventListener('input', function(key) {
              console.log('监听input值:' + element.value);
              _this.obj[attrVal] = element.value;
            })
            this._binding[attrVal]._directives.push({el: element, attr: 'value', _this: _this});
          }

          // 解析innerHtml,替换{{}}里面的数据
          if (element.innerHTML) {
            console.log('innerHtml: {{}}');
            console.log(element.innerHTML);
            let innerHTMLStr = element.innerHTML;
            var matchReg = /(?<={{).*?(?=})/g;
            if (innerHTMLStr.match(matchReg)) {
              for (let attrVal of innerHTMLStr.match(matchReg)) {
                this._binding[attrVal]._directives.push({ el: element, attr: 'innerHTML', _this: _this });
              }
            }
          }
        }
      }

      function increment() {
        obj.number++;
      }
    </script>
</html>

相关文章

网友评论

      本文标题:简单手写小白氏理解vue双向绑定原理

      本文链接:https://www.haomeiwen.com/subject/vqovkltx.html