vue的雙向數(shù)據(jù)綁定

<!DOCTYPE html>
<head>
  <title>vue雙向數(shù)據(jù)綁定</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);
    }
    // 為了初始化這個(gè)構(gòu)造函數(shù),給它添加一 個(gè)_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進(jìn)行處理,重寫data的set和get函數(shù)
    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)等,并在這個(gè)過程中對view與model進(jìn)行綁定
    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,用來綁定更新函數(shù),實(shí)現(xiàn)對DOM元素的更新
    function Watcher(name, el, vm, exp, attr) {
      this.name = name;         //指令名稱,例如文本節(jié)點(diǎn),該值設(shè)為"text"
      this.el = el;             //指令對應(yīng)的DOM元素
      this.vm = vm;             //指令所屬myVue實(shí)例
      this.exp = exp;           //指令對應(yīng)的值,本例如"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>

參考文章: 面試題:你能寫一個(gè)Vue的雙向數(shù)據(jù)綁定嗎?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容