vue源码解析-设计模式

mvvm简图

Model: 服务器上的逻辑
view: 页面展示
ViewModel: 比如vue.js,做为view和model的中间处理

双向绑定简图

设计模式简图

Observe: 监听data数据变化
Dep: 维护观察者列表,列表留存了数据key|value以及改变数据的回调
Watcher: 在compile中调用添加观察者列表(是observe和compile的中间者)

设计模式骨骼代码

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>源码分析</title>
</head>
<style>
#app {
text-align: center;
}
</style>
<body>
<div id="app">
<h2>{{title}}</h2>
<input v-model="name">
<h1>{{name}}</h1>
<button v-on:click="clickMe">click me!</button>
</div>
</body>
<script src="js/observer.js"></script>
<script src="js/watcher.js"></script>
<script src="js/compile.js"></script>
<script src="js/index.js"></script>
<script type="text/javascript">

new Vue({
el: '#app',
data: {
title: 'vue code',
name: 'Yvonne',
},
methods: {
clickMe: function () {
this.title = 'vue code click';
},
},
mounted: function () {
window.setTimeout(() => {
this.title = 'timeout 1000';
}, 1000);
},
});


</script>
</html>

入口index.js

此处将data属性代理到vm上,可以通过get|set触发到data属性的get|set
触发observe递归遍历data对象属性

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
function Vue (options) {
var self = this;
this.data = options.data;
this.methods = options.methods;

Object.keys(this.data).forEach(function (key) {
// 将data属性代理到vm上
self.proxyKeys(key);
});

observe(this.data);
new Compile(options.el, this);
options.mounted.call(this); // 所有事情处理好后执行mounted函数
}

Vue.prototype = {
proxyKeys: function (key) {
var self = this;
Object.defineProperty(this, key, {
enumerable: false,
configurable: true,
get: function () {
return self.data[key];
},
set: function (newVal) {
self.data[key] = newVal;
},
});
},
};

observe.js

递归使用Object.defineProperty()设置创建每个对象属性的getter|setter
getter中返回value外,做新增Dep观察者列表的调用触发
setter中设置newValue外,告知Dep观察列表遍历更新处理

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
function Observer (data) {
this.data = data;
this.walk(data);
}

Observer.prototype = {
walk: function (data) {
var self = this;
Object.keys(data).forEach(function (key) {
self.defineReactive(data, key, data[key]);
});
},
defineReactive: function (data, key, val) {
var dep = new Dep();
var childObj = observe(val);
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function getter () {
if (Dep.target) {
dep.addSub(Dep.target);
}
return val;
},
set: function setter (newVal) {
if (newVal === val) {
return;
}
val = newVal;
dep.notify();
},
});
},
};

function observe (value, vm) {
if (!value || typeof value !== 'object') {
return;
}
return new Observer(value);
}

function Dep () {
this.subs = [];
}
Dep.prototype = {
addSub: function (sub) {
this.subs.push(sub);
},
notify: function () {
this.subs.forEach(function (sub) {
sub.update();
});
},
};
Dep.target = null;

watcher.js

通过Dep.target缓存自己,触发访问data的getter来追加观察者列表,观察者列表存的是Watcher实例(实例对象包含vm、属性名、属性值、回调)
data值改变则通过Observe设置的属性setter回调通知到Dep遍历所有观察者去做更新,触发Watcher实例的回调

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
function Watcher (vm, exp, cb) {
this.cb = cb;
this.vm = vm;
this.exp = exp;
this.value = this.get(); // 将自己添加到订阅器的操作
}

Watcher.prototype = {
update: function () {
this.run();
},
run: function () {
var value = this.vm.data[this.exp];
var oldVal = this.value;
// data值(new)与dep列表值(old)对比,更新dep列表&callback
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal);
}
},
get: function () {
Dep.target = this; // 缓存自己
var value = this.vm.data[this.exp]; // 强制执行监听器里的get函数
Dep.target = null; // 释放自己
return value;
},
};

compile.js

编译解析指令,事件指令则给node添加事件绑定methods中事件,v-model或者是textNode则创建Watcher实例来追加观察者列表
Dom操作采用fragment提高页面性能

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
118
119
function Compile (el, vm) {
this.vm = vm;
this.el = document.querySelector(el);
this.fragment = null;
this.init();
}

Compile.prototype = {
init: function () {
if (this.el) {
this.fragment = this.nodeToFragment(this.el);
this.compileElement(this.fragment);
this.el.appendChild(this.fragment);
} else {
console.log('Dom元素不存在');
}
},
nodeToFragment: function (el) {
var fragment = document.createDocumentFragment();
var child = el.firstChild;
while (child = el.firstChild) {
// 将Dom元素移入fragment中
// console.log(el.childNodes)
// 能循环遍历el是由于appendChild()方法,当被插入的节点已经存在当前文档的文档树中,该节点会先从原位置移除
fragment.appendChild(child);
}
return fragment;
},
compileElement: function (el) {
var childNodes = el.childNodes;
var self = this;
[].slice.call(childNodes).forEach(function (node) {
var reg = /\{\{(.*)\}\}/;
var text = node.textContent;

if (self.isElementNode(node)) {
self.compile(node);
} else if (self.isTextNode(node) && reg.test(text)) {
self.compileText(node, reg.exec(text)[1]);
}
// 递归遍历node
if (node.childNodes && node.childNodes.length) {
self.compileElement(node);
}
});
},
compile: function (node) {
var nodeAttrs = node.attributes;
var self = this;
Array.prototype.forEach.call(nodeAttrs, function (attr) {
var attrName = attr.name;
if (self.isDirective(attrName)) {
var exp = attr.value;
var dir = attrName.substring(2);
if (self.isEventDirective(dir)) { // 事件指令
self.compileEvent(node, self.vm, exp, dir);
} else { // v-model 指令
self.compileModel(node, self.vm, exp, dir);
}
node.removeAttribute(attrName);
}
});
},
compileText: function (node, exp) {
var self = this;
var initText = this.vm[exp];
// 初始化 data => view
this.updateText(node, initText);
// 追加dep列表 data => view
new Watcher(this.vm, exp, function (value) {
self.updateText(node, value);
});
},
compileEvent: function (node, vm, exp, dir) {
var eventType = dir.split(':')[1];
var cb = vm.methods && vm.methods[exp];

if (eventType && cb) {
node.addEventListener(eventType, cb.bind(vm), false);
}
},
compileModel: function (node, vm, exp, dir) {
var self = this;
var val = this.vm[exp];
// 初始化 data => view
this.modelUpdater(node, val);
// 追加dep列表 data => view
new Watcher(this.vm, exp, function (value) {
self.modelUpdater(node, value);
});
// view => data
node.addEventListener('input', function (e) {
var newValue = e.target.value;
if (val === newValue) {
return;
}
self.vm[exp] = newValue;
val = newValue;
});
},
updateText: function (node, value) {
node.textContent = typeof value === 'undefined' ? '' : value;
},
modelUpdater: function (node, value, oldValue) {
node.value = typeof value === 'undefined' ? '' : value;
},
isDirective: function (attr) {
return attr.indexOf('v-') == 0;
},
isEventDirective: function (dir) {
return dir.indexOf('on:') === 0;
},
isElementNode: function (node) {
return node.nodeType == 1;
},
isTextNode: function (node) {
return node.nodeType == 3;
},
};

代码链接