/
vue-class-proxy.html
93 lines (91 loc) · 2.44 KB
/
vue-class-proxy.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
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue 双向绑定</title>
</head>
<body>
<div id="app">
<input type="text" v-model="num">
<input type="button" value="增加" v-click="add">
<input type="button" value="减去" v-click="sub">
<div v-bind="num"></div>
</div>
</body>
<script>
class Vue {
constructor (options) {
this.$el = document.querySelector(options.el)
this.$methods = options.methods
this._binding = {}
this._observe(options.data)
this._compile(this.$el)
}
_pushWatcher (watcher) {
if (!this._binding[watcher.key]) this._binding[watcher.key] = []
this._binding[watcher.key].push(watcher)
}
_observe (data) {
var that = this
this.$data = new Proxy(data, {
set(target,key,value){
let res = Reflect.set(target,key,value)
that._binding[key].map(item => {item.update()})
return res
}
})
}
_compile (root) {
const nodes = Array.prototype.slice.call(root.children)
let data = this.$data
nodes.map(node => {
if(node.children.length > 0) this._complie(node)
if(node.hasAttribute('v-bind')) {
let key = node.getAttribute('v-bind')
this._pushWatcher(new Watcher(node,'innerHTML',data,key))
}
if(node.hasAttribute('v-model')) {
let key = node.getAttribute('v-model')
this._pushWatcher(new Watcher(node,'value',data,key))
node.addEventListener('input',() => {data[key] = node.value})
}
if(node.hasAttribute('v-click')) {
let methodName = node.getAttribute('v-click')
let mothod = this.$methods[methodName].bind(data)
node.addEventListener('click',mothod)
}
})
}
}
class Watcher {
constructor (node,attr,data,key) {
this.node = node
this.attr = attr
this.data = data
this.key = key
}
update () {
this.node[this.attr] = this.data[this.key]
}
}
// 实例化一个Vue 测试用
window.onload = function () {
window.$app = new Vue({
el: '#app',
data:{
num:0
},
methods:{
add(){
this.num++
},
sub(){
this.num--
}
}
})
}
</script>
</html>