Vue2响应式与依赖收集原理

响应式

Vue2的响应式依赖ES5Object.defineProperty,主要使用这个API改写对象的GetterSetter,用来依赖收集与触发更新

依赖收集原理

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

// 工具函数用来判断obj是不是一个object
function isObject (obj) {
return typeof obj === 'object'
&& !Array.isArray(obj)
&& obj !== null
&& obj !== undefined
}

// `observe`函数用来把一个普通的对象转为响应式对象
function observe (obj) {
if (!isObject(obj)) {
throw new TypeError()
}

Object.keys(obj).forEach(key => {
let internalValue = obj[key]
// 每一个属性都有一个独立的依赖收集器
let dep = new Dep()
Object.defineProperty(obj, key, {
get () {
// 这里用来收集依赖
dep.depend()
return internalValue
},
set (newValue) {
const isChanged = internalValue !== newValue
if (isChanged) {
internalValue = newValue
// 如果修改了值,这里用来通知修改
dep.notify()
}
}
})
})
}

window.Dep = class Dep {
constructor () {
this.subscribers = new Set()
}

depend () {
if (activeUpdate) {
// register the current active update as a subscriber
this.subscribers.add(activeUpdate)
}
}

notify () {
// run all subscriber functions
this.subscribers.forEach(subscriber => subscriber())
}
}

// activeUpdate是一个运行函数
let activeUpdate

// 这只是依赖收集的简单示例,示例代码还是存在不少问题的
function autorun (update) {
// 函数wrappedUpdate这里使用闭包,保存了update方法
function wrappedUpdate () {
activeUpdate = wrappedUpdate
update()
activeUpdate = null
}
wrappedUpdate()
}