Vue源码学习-数组监听变化

2,382 阅读1分钟

导言

我们知道,在Vue监听一个对象在 Vue2.x 中使用 Object.defineProperty(),但是这个方法有一些缺点。

  • 其一,就是只能对对象的一个属性进行数据劫持,如果对象中还包含对象,则需要递归使用这个 API
  • 其二,就是无法对数组进行监听, 要实现对数组监听,只能在 Arrar.prototype 和 数组的实例之间 添加一个 使用 Object.defineProperty 做的拦截器
new Vue({
    el : '#app',
    data : {
        nums : []
    },
    methods : {
        add() {
            this.nums.push(1)
        }
    }
})

在上面的例子中,使用了 push 方法改变数组,并不会触发 getter/setter,那该怎么办呢?

追踪变化

哎,咋们简单写一下吧

const nums = [1,2,3];

const ArrayProto = Array.prototype;

const arrayArguments = [];

const ArrayMethods = ['push'];

ArrayMethods.forEach((method) => {
    // 原生方法
    let orginal = ArrayProto[method];

    arrayArguments[method] = function() {
        console.log('push');

        return orginal.apply(this, arguments);
    }
})

// 重点
nums.__proto__ = arrayArguments;

nums.push(1);


console.log(nums)