手动实现MVVM (ES6)

本文最后更新于:2023年3月19日 晚上

本文参考,加以修改:https://segmentfault.com/a/1190000015460479

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>简单版mvvm</title>
</head>
<body>
<div id="app">
<h1>开发语言:{{language}}</h1>
<h2>组成部分:</h2>
<ul>
<li>{{makeUp.one}}</li>
<li>{{makeUp.two}}</li>
<li>{{makeUp.three}}</li>
</ul>
<h2>描述:</h2>
<p>{{describe}}</p>
<input placeholder="123" v-model="makeUp.three" />
</div>
<script src="./MVVM.js"></script>
<script>
// 写法和Vue一样
const mvvm = new Mvvm({
el: "#app",
data: {
language: "Javascript",
makeUp: {
one: "ECMAScript",
two: "文档对象模型(DOM)",
three: "浏览器对象模型(BOM)",
},
describe: "没什么产品是写不了的",
a: 1,
b: 2,
},
mounted() {
console.log("mounted");
},
});
console.log(mvvm);
</script>
</body>
</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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class Mvvm {
constructor(options = {}) {
this.$el = options.el;
this.$data = options.data;
this.$vm = this.initProxyVM();
this.$mounted = options.mounted();
this.initObserve();
this.initComplie();
this.mounted();
return this.$vm;
}

initProxyVM() {
return new Proxy(this, {
get: (target, key, receiver) => {
return this[key] || this.$data[key];
},
set: (target, key, value) => {
return Reflect.set(this.$data, key, value);
},
});
}

initObserve() {
this.$data = this.observer(this.$data);
}

initComplie() {
new Complie(this.$el, this.$vm);
}

mounted() {
this.$mounted && this.$mounted.call(this.$vm);
}

observer(object) {
if (!object || typeof object !== "object") return object;
return new Observe(object);
}
}

class Observe {
constructor(object) {
this.dep = new Dep();
Reflect.ownKeys(object).forEach((key) => {
object[key] = this.observer(object[key]);
});
return this.initProxyObject(object);
}

observer(object) {
if (!object || typeof object !== "object") return object;
return new Observe(object);
}

initProxyObject(object) {
const dep = this.dep;
const self = this;
return new Proxy(object, {
get(target, key, receiver) {
if (Dep.target) {
if (!dep.depSet.includes(Dep.exp)) {
dep.addDep(Dep.target);
dep.addDep(Dep.exp);
}
}
return Reflect.get(target, key, receiver);
},
set(target, key, value) {
const res = Reflect.set(target, key, self.observer(value));
dep.notify();
return res;
},
});
}
}

class Complie {
constructor(el, vm) {
this.$el = document.querySelector(el);
this.$vm = vm;
this.fragment = this.createFragment();
this.complieFragment();
this.$el.appendChild(this.fragment);
}
createFragment() {
const fragment = document.createDocumentFragment();
let firstChild = this.$el.firstChild;
while (firstChild) {
fragment.appendChild(firstChild);
firstChild = this.$el.firstChild;
}
return fragment;
}
complieFragment() {
const childNodesArr = [...this.fragment.childNodes];
childNodesArr.forEach((node) => {
if (this.isElementNode(node)) {
const nodeAttrs = [...node.attributes];
nodeAttrs.forEach((attr) => {
const attrName = attr.name;
const attrValue = attr.value;
if (attrName === "v-model") {
node.addEventListener("input", (e) => {
const keyArr = attrValue.split(".");
if (keyArr.length === 1) {
this.$vm[keyArr[0]] = e.target.value;
} else {
let val = this.$vm;
let key = keyArr.pop();
keyArr.forEach((key) => {
val = val[key];
});
val[key] = e.target.value;
}
});
}
});

// } else if(this.isTextNode(node)){
const text = node.textContent;
const reg = /\{\{(.*?)\}\}/g;
const self = this;
function replaceText() {
node.textContent = text.replace(reg, (matched, placeholder) => {
new Watcher(self.$vm, placeholder, replaceText);
return placeholder.split(".").reduce((a, b) => a[b], self.$vm);
});
}
if (reg.test(text)) {
replaceText();
}
}
});
}

isElementNode(node) {
return node.nodeType === 1;
}
isTextNode(node) {
return node.nodeType === 3;
}
}

class Dep {
static target = null;
static depSet = [];
static exp = null;

constructor() {
this.depSet = [];
}
addDep(dep) {
this.depSet.push(dep);
}
notify() {
this.depSet
.filter((e) => typeof e !== "string")
.forEach((dep) => {
dep.update();
});
}
}

class Watcher {
constructor(vm, exp, fn) {
this.$vm = vm;
this.exp = exp;
this.fn = fn;
Dep.target = this;
Dep.exp = exp;
const arr = exp.split(".");
let val = this.$vm;
arr.forEach((key) => {
val = val[key];
});
Dep.target = null;
}
update() {
let exp = this.exp;
let arr = exp.split(".");
let val = this.$vm;
arr.forEach((key) => {
val = val[key];
});
this.fn(val);
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!