-
Notifications
You must be signed in to change notification settings - Fork 0
/
dvue.js
94 lines (88 loc) · 1.79 KB
/
dvue.js
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
class DVue {
constructor(opts) {
this.$opts = opts;
this.$data = opts.data;
// 代理属性
this.proxyMethods(opts.methods);
this.observe(this.$data);
// 编译模板
this.$compile = new Compile(opts.el, this);
// 触发生命周期
if (opts.created) {
opts.created.call(this);
}
}
/** 代理methods */
proxyMethods(methods) {
Object.keys(methods).forEach((key) => {
Object.defineProperty(this, key, {
get() {
return methods[key].bind(this);
},
});
});
}
/** 代理Data */
proxyData(key) {
Object.defineProperty(this, key, {
get() {
return this.$data[key];
},
set(newVal) {
this.$data[key] = newVal;
},
});
}
/** 添加响应式 */
observe(value) {
if (!value || typeof value !== 'object') return;
Object.keys(value).forEach((key) => {
this.defineReactive(value, key, value[key]);
this.proxyData(key);
});
}
/** 添加响应式 */
defineReactive(obj, key, value) {
// 递归设置监听
this.observe(value);
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
if (Dep.target) {
dep.addDep(Dep.target);
}
return value;
},
set(newVal) {
if (newVal !== value) {
value = newVal;
dep.notify();
}
},
});
}
}
class Dep {
constructor() {
this.deps = [];
}
addDep(watcher) {
this.deps.push(watcher);
}
notify() {
this.deps.forEach((dep) => dep.update());
}
}
class Watcher {
constructor(vm, key, cb) {
this.vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.vm[key];
Dep.target = null;
}
update() {
this.cb.call(this.vm, this.vm[this.key]);
}
}