Vue is how to achieve a two-way binding?

Hijack object using Object.defineProperty accessor, when a property value change we can get changed, and then a subsequent response to the change, in a similar procedure by vue3.0 Proxy proxy object.

// 这是将要被劫持的对象
const data = {
  name: '',
};

function say(name) {
  if (name === '古天乐') {
    console.log('给大家推荐一款超好玩的游戏');
  } else if (name === '我是新数据') {
    console.log('戏我演过很多,可游戏我只玩贪玩懒月');
  } else {
    console.log('来做我的兄弟');
  }
}

// 遍历对象,对其属性值进行劫持
Object.keys(data).forEach(function(key) {
  Object.defineProperty(data, key, {
    enumerable: true,
    configurable: true,
    get: function() {
      console.log('get');
    },
    set: function(newVal) {
      // 当属性值发生变化时我们可以进行额外操作
      console.log(`大家好,我系${newVal}`);
      say(newVal);
    },
  });
});

data.name = '我是新数据';

Proxy pros and cons and Object.defineProperty comparison?

Proxy advantages as follows:

1.Proxy can not directly monitor the object properties
2.Proxy directly monitor changes in the array
3.Proxy up to 13 different interception method is not limited to apply, ownKeys, deleteProperty, has like are not available Object.defineProperty
4. Proxy returns a new object, we can only achieve the purpose of operating the new object, and Object.defineProperty can only traverse the object properties directly modify
5.Proxy as the new standard browser vendors will be the focus of ongoing performance optimization, which is legendary the new standard of performance bonus

Object.defineProperty the following advantages:

Compatibility, support for IE9

Guess you like

Origin www.cnblogs.com/IT123/p/11284104.html