Vue.js 响应式原理

Vue.js 响应式原理

简述Vue响应式原理

  • 创建vue类型,把data成员注入vue实例,转化为get和set
  • vue内部会调用Observer和Compiler
  • Observer数据劫持,对data的数据进行监听,如果数据发生变化,获取最新值通知Dep发布者
  • Compiler解析指令,和插值表达式替换相应的数据
  • Dep发布者通知观察者,数据发生变化
  • Watcher更新视图

Vue响应式原理

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
vue.js

class Vue {
constructor (options) {
// 通过属性保存选项的数据
this.$options = options || {}
this.$data = options.data || {}
this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el
// 把data中的成员转换成getter和setter,注入vue实例
this._proxyData(this.$data)
// 调用observer对象,监听数据变化
new Observer(this.$data)
// 解析指令和插值表达式
new Compiler(this)
}

_proxyData (data) {
// 遍历data中所有属性
Object.keys(data).forEach(key => {
// 把data的属性注入到vue实例中
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get () {
return data[key]
},
set (newValue) {
if (newValue === data[key]) {
return
}
data[key] = newValue
}
})
})
}
}
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
observer.js

class Observer {
constructor (data) {
this.walk(data)
}
// 遍历data对象
walk (data) {
if (!data || typeof data !== 'object') return
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
// 对data转换成响应式
defineReactive (obj, key, val) {
let that = this
// 负责收集依赖,并发送通知
let dep = new Dep()
// 假如data中的key值是对象,需要将key对象的属性转换响应式
this.walk(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get () {
Dep.target && dep.addSub(Dep.target)
return val
},
set (newVal) {
if (newVal === val) return
val = newVal
// data的key值进行更新,需要重新转换响应式
that.walk(obj)
// 数据发生变化,进行通知
dep.notify()
}
})
}
}
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
compiler.js

class Compiler {
constructor (vm) {
this.el = vm.$el
this.vm = vm
this.compile(this.el)
}

// 编译模版,处理文本节点和元素节点
compile (el) {
let childNodes = el.childNodes

Array.from(childNodes).forEach(node => {
// 处理文本节点
if (this.isTextNode(node)) {
this.compileText(node)
} else if (this.isElementNode(node)) {
// 元素节点
this.compileElement(node)
}

// node存在子节点,进行递归调用
if (node.childNodes && node.childNodes.length) {
this.compile(node)
}
})
}

// 编译文本节点,处理插值表达式
compileText (node) {
// 匹配文本的插值表达式 {{ msg }}
let reg = /\{\{(.+?)\}\}/
let value = node.textContent
if (reg.test(value)) {
// 去掉插值表达式中的空格
let key = RegExp.$1.trim()
node.textContent = value.replace(reg, this.vm[key])

// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
}

// 编译元素节点,处理元素指令
compileElement (node) {
// 遍历所有属性节点
Array.from(node.attributes).forEach(attr => {
// 判断是否有指令
let attrName = attr.name
if (this.isDirective(attrName)) {
attrName = attrName.substr(2)
let key = attr.value
this.update(node, key, attrName)
}
})
}

update (node, key, attrName) {
let updateFn = this[attrName + 'Updater']
updateFn && updateFn.call(this, node, this.vm[key], key)
}

// 处理v-text
textUpdater (node, value, key) {
node.textContent = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}

// 处理v-model
modelUpdater (node, value, key) {
node.value = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.value = newValue
})

// 双向绑定
node.addEventListener('input', () => {
this.vm[key] = node.value
})
}

// 判断是否是指令
isDirective (attrName) {
return attrName.startsWith('v-')
}

// 判断节点是否是文本节点
isTextNode (node) {
return node.nodeType === 3
}

// 判断是否是元素节点
isElementNode (node) {
return node.nodeType === 1
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
dep.js

class Dep {
constructor () {
// 存储所有的观察者
this.subs = []
}

// 添加观察者
addSub (sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}

// 发送通知
notify () {
this.subs.forEach(sub => {
sub.update()
})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
watcher.js

class Watcher {
constructor (vm, key, cb) {
this.vm = vm
// data中的属性名称
this.key = key
// 回调函数负责更新视图
this.cb = cb

// 把watcher对象记录到Dep类的静态属性target
Dep.target = this
// 触发get方法,在get方法中会调用addSub
this.oldValue = vm[key]
Dep.target = null
}

// 当数据发生变化的时候更新视图
update () {
let newValue = this.vm[this.key]
if (this.oldValue === newValue) return
this.cb(newValue)
}
}
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
<div id="app">
<h2>插值表达式</h2>
<div>{{msg}}</div>
<div>{{count}}</div>

<h2>指令</h2>
<div v-text="msg"></div>
<div v-text="count"></div>

<h2>双向绑定</h2>
<input type="text" v-model="msg">
<input type="text" v-model="count">
</div>
<script src="dep.js"></script>
<script src="watcher.js"></script>
<script src="observer.js"></script>
<script src="compiler.js"></script>
<script src="vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'Hello',
count: 100
}
})
</script>