Vue解析-数据响应系统

Vue解析-数据响应系统

实例对象代理访问数据 data

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
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: null,
set: null
}

function proxy(target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter() {
console.log('han)
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter(val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}

function Data() {
this.data = {
a: 1,
b: 2
}

for(let key in this.data) {
proxy(this, 'data', key)
}
}

let data = new Data()
console.log(data.a , data.b) // 1 2

data.a = 10
data.b = 20
console.log(data.a , data.b) // 10 20

基本实现思路

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
let target = null
let data = { price: 5, quantity: 2 }

class Dep {
constructor () {
this.subscribers = []
}

depend () {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target)
}
}

notify () {
this.subscribers.forEach(sub => sub())
}
}

Object.keys(data).forEach(key => {
let internalValue = data[key]
const dep = new Dep()

Object.defineProperty(data, key, {
get () {
dep.depend() // Remember the target we'er running
return internalValue
},
set (newVal) {
internalValue = newVal
dep.notify() // Re-run stored functions
}
})
})

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

watcher(() => {
data.total = data.price * data.quantity
})

console.log(data.price) // 5
console.log(data.quantity) // 3
console.log(data.total) // 10

data.price = 20
console.log(data.total) // 40

data.quantity = 3
console.log(data.total) // 60