Home  >  Article  >  Web Front-end  >  Introduction to the method of using Proxy to implement two-way binding (code)

Introduction to the method of using Proxy to implement two-way binding (code)

不言
不言forward
2019-03-20 10:08:332002browse

This article brings you an introduction to the method (code) of using Proxy to achieve two-way binding. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Foreword: vue3.0 uses Proxy to implement two-way binding, so let’s try the implementation method first.

1 Object.defineProperty implementation

The original implementation of vue2 uses Object.defineProperty to monitor set, but it cannot monitor the array setting value directly by subscripting the array.

function observe(data) {
  if (!data || typeof data !== 'object') {
      return;
  }
  // 取出所有属性遍历
  Object.keys(data).forEach(function(key) {
      defineReactive(data, key, data[key]);
  });
};
function defineReactive(data, key, val) {
  observe(val); // 监听子属性
  Object.defineProperty(data, key, {
      enumerable: true, // 可枚举
      configurable: false, // 不能再重写defineProperty
      get: function() {
          return val;
      },
      set: function(newVal) {
          console.log('-------通知订阅者--------')
          val = newVal;
      }
  });
}

2 Use Proxy to implement

The main principle of using Proxy is to create a new Proxy object to proxy your data value. One thing to note is that for the array method In terms of operation, there will be two assignment operations, one to add a value, and one to change its length value. For array subscripts that cannot be monitored by Object.defineProperty, Proxy can monitor it.

function observe(data) {
    if (!data || typeof data !== 'object') {
        return;
    }
    // 取出所有属性遍历
    Object.keys(data).forEach(function(_k) {
        // Proxy不允许绑定在非对象上
        if (data[_k] && typeof data[_k] === 'object') {
            data[_k] = defineReactive(data[_k]);
        }
    });
}

function defineReactive(data) {
  return new Proxy(data, {
    set(target, key, value, proxy) {
        // 进行数组操作时,会进行两次set 一次数据改变,一次length改变,两次改变data的值是不变,因此不应该多分发一次消息
      if (
        Object.prototype.toString.call(data) === "[object Array]" &&
        key === "length"
      ) {
        Reflect.set(target, key, value, proxy);
        return true;
      }
      observe(data);
      Reflect.set(target, key, value, proxy);
      console.log('-------通知订阅者--------')
      return true;
    }
  });

This article has ended here. For more exciting content, you can pay attention to the JavaScript Tutorial Video column of the PHP Chinese website!

The above is the detailed content of Introduction to the method of using Proxy to implement two-way binding (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete