web前端技术博客
您当前的位置:web前端 > vue.js

vue中修改数组的方法

作者:只会切图的前端 发布时间:2021-03-30 15:34:37 浏览量:19

vue 中调用数组原始方法为什么也会响应式。
对数组中可修改原数组的方法进行了响应式处理,触发数据更新。
并对添加进数组的元素也做了依赖收集,当新添加的元素发生改变时也能触发数据更新。
源码如下:

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
//会修改原数组的方法
const methodsToPatch = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
];
 
methodsToPatch.forEach(function (method) {
    const original = arrayProto[method]
    def(arrayMethods, method, function mutator(...args) {
        const result = original.apply(this, args)
        const ob = this.__ob__
        let inserted
        //对插入的元素进行observeArray
        switch (method) {
            case 'push':
            case 'unshift':
                inserted = args
                break
            case 'splice':
                inserted = args.slice(2)
                break
        }
        if (inserted) ob.observeArray(inserted)
        // notify change
        ob.dep.notify()
        return result
    })

})

发表评论
验证码:
联系我
粤ICP备17092958号