vue - 双向绑定

236 阅读1分钟

2.x通过defineProperty来劫持一个对象,通过里面的get,set方法可以操作获取或者赋值时的操作

function def (obj, key, val, enumerable) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true,
    get : function(){ 
          return this.tmp // 返回tmp修改数据 
    }, 
    set : function(value){     
          this.tmp=value // 获取传入的value,赋值给tmp 
    },
  });
}
  • 无法监听数组索引和长度发生变化的 但是兼容性比proxy强
  • 会修改源对象,因为是引用 vue3通过proxy代理整个对象
 let fruit = {
     "apple": 2,
     "pear": 22,
     "peach": 222
  }
  let proxy = new Proxy(fruit, {
    get: function (obj, prop) {
      return prop in obj ? obj[prop] : undefined

    },
    set: function (obj, prop, newVal) {
      obj[prop] = newVal
      console.log("newVal", newVal) // 输出 newVal 888
      return true;
    }
  })
  proxy.apple = 888
  • Proxy代理可以劫持对象属性的添加,defineProperty用this.$set来实现
  • proxy支持12种方法

image.png