vue3响应式的实现

非递归监听,只有第一层改变才会触发界面更新

shallowReactive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function shallowReactive(obj){
return new Proxy(obj,{
get(obj,key){
return obj[key]
},
set(obj,key,value){
obj[key] = value
return true
}
})
}
var obj = {name:'doreen'}
var state = new shallowReactive(obj)
state.name = 'sherry' // { name: 'sherry' }

shallowRef

在shallowReactive的基础上,在外部封装一层value,所以他的第一层是value,只有value改变才会触发界面更新

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function shallowRef(val){
return shallowReactive({value: val})
}
function shallowReactive(obj){
return new Proxy(obj,{
get(obj,key){
return obj[key]
},
set(obj,key,value){
obj[key] = value
return true
}
})
}

var obj = {name:'doreen'}
var state = new shallowRef(obj)
state.value.name = 'haha' // { value: { name: 'haha' } }

shallowReadonly

1
2
3
4
5
6
7
8
9
10
function shallowReadonly(obj) {
return new Proxy(obj, {
get(obj, key) {
return obj[key]
},
set(obj, key, value) {
console.warn('只读 不能被赋值')
}
})
}

非递归监听,每一层改变都会触发更新。原理是把每一层进行proxy封装

reactive

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

function reactive(obj) {
if (typeof obj === 'object') {
if (obj instanceof Array) {
obj.forEach((item, index) => {
if (typeof item === 'object') {
obj[index] = reactive(item)
}

})
} else {
for (let key in obj) {
let item = obj[key];
if (typeof item === 'object') {
obj[key] = reactive(item)
}
}
}
} else {
console.warn(`${obj} is not object`)
}
return new Proxy(obj, {
get(obj, key) {
return obj[key]
},
set(obj, key, value) {
obj[key] = value
return true
}
})
}

ref

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
function ref(val) {
return reactive({ value: val })
}
function reactive(obj) {
if (typeof obj === 'object') {
if (obj instanceof Array) {
obj.forEach((item, index) => {
if (typeof item === 'object') {
obj[index] = reactive(item)
}

})
} else {
for (let key in obj) {
let item = obj[key];
if (typeof item === 'object') {
obj[key] = reactive(item)
}
}
}
} else {
console.warn(`${obj} is not object`)
}
return new Proxy(obj, {
get(obj, key) {
console.log(obj, key)
return obj[key]
},
set(obj, key, value) {
obj[key] = value
console.log(obj)
return true
}
})
}

readonly

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
function readonly(obj) {
if (typeof obj === 'object') {
if (obj instanceof Array) {
obj.forEach((item, index) => {
if (typeof item === 'object') {
obj[index] = readonly(item)
}

})
} else {
for (let key in obj) {
let item = obj[key];
if (typeof item === 'object') {
obj[key] = readonly(item)
}
}
}
} else {
console.warn(`${obj} is not object`)
}
return new Proxy(obj, {
get(obj, key) {
return obj[key]
},
set(obj, key, value) {
console.warn('不能被赋值')
}
})
}

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2023 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信