-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvue依赖收集.html
117 lines (97 loc) · 2.96 KB
/
vue依赖收集.html
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 依赖收集</title>
</head>
<style type="text/css">
</style>
<body>
<script>
class Dep {
constructor() {
this.deps = []
}
depend() {
if (Dep.target && this.deps.indexOf(Dep.target) === -1) {
this.deps.push(Dep.target)
}
}
notify() {
this.deps.forEach((dep) => {
dep()
})
}
}
Dep.target = null
// 同样的道理,我们对observable和watcher都进行一定的封装与优化,使这个响应式系统变得模块化:
class Observable {
constructor(obj) {
return this.walk(obj)
}
walk(obj) {
const keys = Object.keys(obj)
keys.forEach((key) => {
this.defineReactive(obj, key, obj[key])
})
return obj
}
defineReactive(obj, key, val) {
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
dep.depend()
return val
},
set(newVal) {
val = newVal
dep.notify()
}
})
}
}
class Watcher {
constructor(obj, key, cb, onComputedUpdate) {
this.obj = obj
this.key = key
this.cb = cb
this.onComputedUpdate = onComputedUpdate
return this.defineComputed()
}
defineComputed() {
const self = this
const onDepUpdated = () => {
const val = self.cb()
this.onComputedUpdate(val)
}
Object.defineProperty(self.obj, self.key, {
get() {
Dep.target = onDepUpdated
const val = self.cb()
Dep.target = null
return val
},
set() {
console.error('计算属性无法被赋值!')
}
})
}
}
// 然后我们来跑一下:
const hero = new Observable({
health: 3000,
IQ: 150
})
new Watcher(hero, 'type', () => {
return hero.health > 4000 ? '坦克' : '脆皮'
}, (val) => {
console.log(`我的类型是:${val}`)
})
console.log(`英雄初始类型:${hero.type}`)
hero.health = 5000
// -> 英雄初始类型:脆皮
// -> 我的类型是:坦克
// https://www.cnblogs.com/ajianbeyourself/p/8962813.html
</script>
</body>
</html>