-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvvm.html
137 lines (122 loc) · 3.01 KB
/
mvvm.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>my-tiny-vue</title>
<script>
class Watcher {
constructor() {
Dep.target = this
}
update() {
console.log('视图更新了~~~~!!')
}
}
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => {
sub.update()
})
}
}
Dep.target = null
class Vue {
constructor(options) {
this.init(options)
}
init(options) {
// const el = document.querySelector(options.el)
this.$options = options
for (const key in options.methods) {
this[key] = options.methods[key]
}
this._initState()
/* 新建一个 Watcher 观察者对象,这时候 Dep.target 会指向这个 Watcher 对象 */
new Watcher()
/* 在这里模拟 render 的过程,为了触发 message 属性的 get 函数 */
console.log('render~', this.message)
// this._compile(el, options)
}
_initState() {
const dataFn = this.$options.data
const data = this._data = dataFn ? (typeof dataFn === 'function' ? dataFn() : dataFn) : {}
const keys = Object.keys(data)
let i = keys.length
let key
while (i--) {
key = keys[i]
this._proxy(key)
}
this._observer(data)
}
_observer(data) {
if (!data || (typeof data !== 'object')) {
return
}
Object.keys(data).forEach(key => {
this._defineReactive(data, key, data[key])
})
}
_defineReactive(obj, key, val) {
const dep = new Dep()
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
get: function reactiveGetter() {
console.log(23333, Dep.target)
dep.addSub(Dep.target)
return val
},
set: function reactiveSetter(newVal) {
console.log('newVal:', newVal, val)
if (newVal === val) return
dep.notify()
}
})
}
_proxy(key) {
const self = this
Object.defineProperty(self, key, {
configurable: true,
enumerable: true,
get: function proxyGetter() {
return self._data[key]
},
set: function proxySetter(val) {
self._data[key] = val
}
})
}
_compile () {
}
}
</script>
</head>
<body>
<div id="app"></div>
<script>
let vm = new Vue({
// el: '#app',
data() {
return {
message: 1
}
},
methods: {
increase() {
this.message += 1
}
}
})
vm.message = 'hello word!'
</script>
</body>
</html>