-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvvm.js
50 lines (44 loc) · 1.33 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
class MVVM {
constructor(options) {
const vm = this
this.$options = options || {};
this._data = this.$options.data;
this.$vm = this
this._init(vm)
}
_init (vm) {
// 实现 vm.xxx => vm_data.xxx
this._proxyData(vm, '_data')
// 初始化计算属性
this._initComputed(vm);
observe(vm.$options.data, this);
this.$compile = new Compile(vm.$options.el || document.body, this)
}
_proxyData (vm, sourceKey) {
Object.keys(this._data).forEach((key) => {
Object.defineProperty(vm, key, {
configurable: false,
enumerable: true,
get () {
return this[sourceKey][key]
},
set (val) {
this[sourceKey][key] = val
}
});
});
}
_initComputed (vm) {
let computed = this.$options.computed;
if (typeof computed === 'object') {
Object.keys(computed).forEach((key) => {
Object.defineProperty(vm, key, {
get: typeof computed[key] === 'function'
? computed[key]
: computed[key].get,
set: function () { }
});
});
}
}
}