vue 双向绑定示例

// 订阅者
function Watcher(el, props, data, key){
  this.el = el;
  this.props = props;
  this.data = data;
  this.key = key;
  this.update();
}
Watcher.prototype.update = function(){
  // 元素.属性 = 值
  this.el[this.props] = this.data[this.key];
}
// 双向绑定
Zhang.prototype.compile = function(el){
  const nodes = el.children;
  for(let i=0; i<nodes.length; i++){
    const node = nodes[i];
    this.compile(node);
    if(node.hasAttribute("z-on:click")){
      const attrValue = node.getAttribute("z-on:click");
      // call返回的是对象 bind返回的是函数
      node.addEventListener("click", this.$options.methods[attrValue].bind(this.$data));
      console.log(this.$data);
      // node.addEventListener("click", ()=>{
      //   this.$options.methods[attrValue].call(this.$data);
      // })
    }
    if(node.hasAttribute("z-html")){
      const attrValue = node.getAttribute("z-html");
      // 增加订阅者
      this.binds[attrValue].push(new Watcher(node, "innerHTML", this.$data, attrValue));
    }
    if(node.hasAttribute("z-text")){
      const attrValue = node.hasAttribute("z-text");
      // 增加订阅者
      this.binds[attrValue].push(new Watcher(node, "innerHTML", this.$data, attrValue));
    }
    if(node.hasAttribute(":value")){
      const attrValue = node.hasAttribute(":value");
      // 增加订阅者
      this.binds[attrValue].push(new Watcher(node, "value", this.$data, attrValue));
    }
    if(node.hasAttribute("z-model")){
      const attrValue = node.hasAttribute("v-model");
      node.addEventListener("input", (e)=>{
        this.$data[attrValue] = e.target.value;
      })
      // 增加订阅者
      this.binds[attrValue].push(new Watcher(node, "value", this.$data, attrValue));
    }
  }
}

你可能感兴趣的:(vue.js,前端)