vue的双向数据绑定

<!DOCTYPE html>
<head>
  <title>vue双向数据绑定</title>
</head>
<body>
  <div id="app">
    <h2 v-bind='number'></h2>
    <form>
      <input v-model='number' type="text" />
    </form>
  </div>
  <script>
    function dataBind(options){
      this._init(options);
    }
    // 为了初始化这个构造函数,给它添加一 个_init属性
    dataBind.prototype._init = function(options){
      this.$options = options;
      this.$el = document.querySelector(options.el);
      this.$data = options.data;
      this.$methods = options.methods;

      this._binding = {};
      this._observe(this.$data);
      this._complie(this.$el);
    }
    // 对data进行处理,重写data的set和get函数
    dataBind.prototype._observe = function(obj){
      var value;
      for(key in obj){
        if(obj.hasOwnProperty(key)){
          this._binding[key] = {
            _directives:[]
          };
          value = obj[key];
          if(typeof value === 'object'){
            this._observe(value);
          }
          var binding = this._binding[key];
          Object.defineProperty(this.$data,key,{
            enumerable:true,
            configurable:true,
            get:function(){
              console.log(`get${value}`);
              return value;
            },
            set:function(newVal){
              console.log(`set${value}`);
              if(value!==newVal){
                value = newVal;
                binding._directives.forEach(function(item){
                  item.update();
                })
              }
            }
          })
        }
      }
    }
    // 解析我们的指令(v-bind,v-model,v-click)等,并在这个过程中对view与model进行绑定
    dataBind.prototype._complie = function(root){
      var _this = this;
      var nodes = root.children;
      for(var i=0;i<nodes.length;i++){
        var node = nodes[i];
        if(node.children.length){
          this._complie(node);
        }
        if(node.hasAttribute('v-model')&&(node.tagName == 'INPUT'||node.tagName == 'TEXTAREA')){
          node.addEventListener('input',(function(key){
            var attrVal = node.getAttribute('v-model');
          _this._binding[attrVal]._directives.push(new Watcher(
            'input',
            node,
            _this,
            attrVal,
            'value'
          ))

          return function() {
            _this.$data[attrVal] =  nodes[key].value;
          }
          })(i))
        }

        if (node.hasAttribute('v-bind')) {
          var attrVal = node.getAttribute('v-bind');
          _this._binding[attrVal]._directives.push(new Watcher(
            'text',
            node,
            _this,
            attrVal,
            'innerHTML'
          ))
        }


      }
    }
    // 指令类Watcher,用来绑定更新函数,实现对DOM元素的更新
    function Watcher(name, el, vm, exp, attr) {
      this.name = name;         //指令名称,例如文本节点,该值设为"text"
      this.el = el;             //指令对应的DOM元素
      this.vm = vm;             //指令所属myVue实例
      this.exp = exp;           //指令对应的值,本例如"number"
      this.attr = attr;         //绑定的属性值,本例为"innerHTML"

      this.update();
    }

    Watcher.prototype.update = function () {
      this.el[this.attr] = this.vm.$data[this.exp];
    }

    window.onload = function() {
      var app = new dataBind({
        el:'#app',
        data: {
          number: 0
        }
      })
    }
  </script>
</body>
</html>

参考文章: 面试题:你能写一个Vue的双向数据绑定吗?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容