# Vue.js 依赖收集
# 为什么要依赖收集
先看下面这段代码
new Vue({
template: `<div>
<span>text1:</span> {{text1}}
<span>text2:</span> {{text2}}
<div>`,
data: {
text1: 'text1',
text2: 'text2',
text3: 'text3'
}
});
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
按照之前《响应式原理》中的方法进行绑定则会出现一个问题——text3 在实际模板中并没有被用到,然而当 text3 的数据被修改(this.text3 = 'test')的时候,同样会触发 text3 的 setter 导致重新执行渲染,这显然不正确。
# 先说说 Dep
当对 data 上的对象进行修改值的时候会触发它的 setter,那么取值的时候自然就会触发 getter 事件,所以我们只要在最开始进行一次 render,那么所有被渲染所依赖的 data 中的数据就会被 getter 收集到 Dep 的 subs 中去。在对 data 中的数据进行修改的时候 setter 只会触发 Dep 的 subs 的函数。
定义一个依赖收集类 Dep。
class Dep {
constructor () {
this.subs = [];
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
notify () {
// stabilize the subscriber list first
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)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 开始依赖收集
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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
将观察者 Watcher 实例赋值给全局的 Dep.target,然后触发 render 操作只有被 Dep.target 标记过的才会进行依赖收集。有 Dep.target 的对象会将 Watcher 的实例 push 到 subs 中,在对象被修改触发 setter 操作的时候 dep 会调用 subs 中的 Watcher 实例的 update 方法进行渲染。