vue2.X数据绑定原理

vue2.0数据绑定原理

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
let data = { price: 5, quantity: 2 }
let target = null
class Dep {
constructor () {
this.subscribers = []
}
//记录target
depend () {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target)
}
}
//调用每一个target
notify () {
this.subscribers.forEach(sub => sub())
}
}
Object.keys(data).forEach(key => {
let internalValue = data[key]
//为该属性添加依赖类
const dep = new Dep()

Object.defineProperty(data, key, {
get() {
dep.depend()
return internalValue
},
set(newVal) {
internalValue = newVal
dep.notify()
}
})
})
function watcher(myFun) {
//全局属性target
target = myFun
target()
target = null
}
watcher(() => {
data.total = data.price * data.quantity
})
1
2
3
4
5
data.total
10
data.price = 20
data.total
40

步骤解析:

  1. 调用target,执行data.total = data.price * data.quantity,触发data.price的getter,执行dep.depand(),将target记录下来,data.quantity同理
  2. data.price = 20触发data.price的setter,执行dep.notify(),将subscribers中记录的每一个target执行一次。

参考