仿Vue.js实现数据绑定

之前在微信公众号上看到一篇文章《Vue.js是如何做到数据响应的?》详细讲解了Vue.js实现数据响应的基本原理,非常的不错。但是,因为是微信公众号所以不利于搜索引擎的抓取,怕以后找不到,所以在自己的博客中再次的记载下。

核心思想

  • class
  • 对象的 defineProperty 属性
  • 观察者模式

完整示例代码:

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
//绑定的数据
let data = {
"pirce" : 10,
"quantity" : 2,
"total" : 0
}

//目标函数寄存器
let target = null

//时间寄存器
class Dep {
constructor () {
this.subscribers = []
}
depend () {
if(target && !this.subscribers.includes(target)){
this.subscribers.push(target)
}
}
notify () {
this.subscribers.forEach(sub => sub())
}
}

//初始化
//利用 Objeect.defineProperty 属性给data中的每个key都绑定上 set() , get() 方法
Object.keys(data).forEach(key => {
let internalValue = data[key]
const dep = new Dep()

Object.defineProperty(data, key, {
set (newValue) {
internalValue = newValue
dep.depend()
},

get () {
dep.notify()
return internalValue
}
})

})

function watcher(funName) {
target = funName
target()
target = null
}

watcher(() => data.total = data.pirce * data.quantity)

console.log(data.total)
data.quantity = 4
console.log(data.total)

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~