How vue was mutating array method? E.g. push, pop, splice or the like

1. Why array is treated separately

In the conventional phase Vue, responsive to treatment with Object.defineProperty data is intercepted, and this method can not monitor internal changes to the array, the array length changes, changes in the array taken like, we need to perform these operations hack, let vue able to monitor changes in them.

2. how to array processing

methodsToPatch.forEach(function(method) {
    // cache original method
    // 获取原方法
    var original = arrayProto[method];
    // def方法重新定义arrayMethods的method方法,然后将新的取值方法赋值
    def(arrayMethods, method, function mutator() {
      var args = [],
        len = arguments.length;
      while (len--) args[len] = arguments[len];

      var result = original.apply(this, args);
      var ob = this.__ob__;
      var inserted;
      switch (method) {
        case 'push':
        case 'unshift':
          // [].push(1),[].unshift(1)
          // arg = [1]
          inserted = args;
          break
        case 'splice':
          // [1,2,3].splice(0,1,1)
          // 第三个参数为插入的值
          inserted = args.slice(2);
          break
      }
      if (inserted) { ob.observeArray(inserted); }
      // 监听变化,如果不是插入操作直接循环响应
      // 如果是去除数组参数方法,触发一次notify将会重新计算
      // 如果仅仅是数字数据,任何操作只需要再次执行一次notify则可以
      // 但是如果新增的是一个对象类型,就需要重新监听
      // 为什么用角标和length属性不能监听的原因是因为无法触发obj的get方法,所以没法动态监听
      // notify change
      ob.dep.notify();
      return result
    });
  });

As the questions asked, vue to push, pop, splice and other methods of the hack, hack is very simple, if adding a new object, the new object type of response as to how responsive technology please refer to the vue source.
For example unshift will push and push a new object to the array (either from the front or from the rear), the record is added to the object, and to convert the object method calls Observe added to responsive objects, the method for the splice, if the new object is added to the formula of the object response.
The final step is to throw out an array of changes, reminding the viewer to be updated.

3. Problems

For if the direct cause of the defect Object.defineProperty change the array subscript is not a hack, due to this point, vue provides $ set method, of course, it is the latest solution to listen using the Proxy object, but the drawback Proxy compatibility, may will give up in order to facilitate the compatibility and performance of it, everything must look particularly great decision.

4.ps

3.0 do not know when to come out, I can not wait until

Published 229 original articles · won praise 80 · views 410 000 +

Guess you like

Origin blog.csdn.net/qq_34629352/article/details/104960152