-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvvm.js
56 lines (45 loc) · 1.34 KB
/
mvvm.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
import {observe} from './observe';
import Watcher from './watcher';
import Compile from './compile';
class MVVM {
constructor(options = {}) {
this.$options = options;
this._data = this.$options.data;
// 数据代理实现vm.xxx -> vm._data.xxx
Object.keys(this._data).forEach((key) => {
this._proxyData(key);
})
this._initComputed();
// 遍历data给属性添加setter getter
observe(this._data);
this.$compile = new Compile(options.el || document.body, this);
}
$watch(key, cb) {
new Watcher(this, key, cb);
}
_proxyData(key) {
Object.defineProperty(this, key, {
configurable: false,
enumerable: true,
get() {
return this._data[key];
},
set(newVal) {
this._data[key] = newVal;
}
})
}
_initComputed() {
const computed = this.$options.computed;
if (typeof computed === 'object') {
Objectkeys(computed).forEach((key) => {
Object.defineProperty(this, key, {
get: typeof computed[key] === 'function' ? computed[key] : computed[key].get,
set() {
}
})
})
}
}
}
export default MVVM;