Vue依赖收集

61 阅读2分钟

为什么要做依赖收集呢?

不妨先看一点点代码。

new Vue({
    template: 
        `<div>
            <span>text1:</span> {{text1}}
            <span>text2:</span> {{text2}}
        <div>`,
    data: {
        text1: 'text1',
        text2: 'text2',
        text3: 'text3'
    }
});

按照 响应式原理 来说。data下的所有属性都会被劫持到,但是模版中并没有用到text3,如果更改了text3,同样会触发set方法,导致视图更新。显然这不合理。

先说说Dep

当对data上的对象进行修改值的时候会触发它的setter,那么取值的时候自然就会触发getter事件,所以我们只要在最开始进行一次render,那么所有被渲染所依赖的data中的数据就会被getter收集到Dep的subs中去。在对data中的数据进行修改的时候setter只会触发Dep的subs的函数。

class Dep {
    constructor () {
        this.subs = [];
    }

    addSub (sub: Watcher) {
        this.subs.push(sub)
    }

    removeSub (sub: Watcher) {
        remove(this.subs, sub)
    }
    notify () {
        const subs = this.subs.slice()
        for (let i = 0, l = subs.length; i < l; i++) {
            subs[i].update()
        }
    }
}

function remove (arr, item) {
    if (arr.length) {
        const index = arr.indexOf(item)
        if (index > -1) {
            return arr.splice(index, 1)
        }
    }
}

Watcher

订阅者,当依赖手机的时候会被addSub到sub中,在修改data中的数据时会触发dep对象的notify,通知所有的watcher对象去修改对应视图。

class Watcher {
    constructor (vm, expOrFn, cb, options) {
        this.cb = cb;
        this.vm = vm;

        // 在这里将观察者本身赋值给全局的target,只有被target标记过的才会进行依赖收集
        Dep.target = this;
        // 触发渲染操作进行依赖收集
        this.cb.call(this.vm);
    }

    update () {
        this.cb.call(this.vm);
    }
}

依赖收集

将观察者Watcher实例赋值给全局的Dep.target,然后触发render操作只有被Dep.target标记过的才会进行依赖收集。有Dep.target的对象会将Watcher的实例push到subs中,在对象被修改触发setter操作的时候dep会调用subs中的Watcher实例的update方法进行渲染。

class Vue {
    constructor(options) {
        this._data = options.data;
        observer(this._data, options.render);
        let watcher = new Watcher(this, );
    }
}

function defineReactive (obj, key, val, cb) {
    // 在闭包内存储一个Dep对象
    const dep = new Dep();

    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
            if (Dep.target) {
                // Watcher对象存在全局的Dep.target中
                dep.addSub(Dep.target);
            }
        },
        set:newVal=> {
            // 只有之前addSub中的函数才会触发
            dep.notify();
        }
    })
}

Dep.target = null;