关于Vue3的响应式总结
1. Vue2和Vue3的响应式区别
a. 从根本上来看,Vue2响应式是使用Object.defineProperty来实现的,而Vue3是使用Proxy来实现的
b. Vue2的响应式无法对数据进行相应,无法对object的属性增加和删除进行响应
c. 从性能上来说,Vue3性能上优于Vue2
2. Vue3的相应实现原理
let data = { text: '123' }
const obj = new Proxy(data, {
get(target, key) {
return target[key]
}
set(target, key, newVal) {
target[key] = newVal
return true
}
})
let activeFun;
const obj = new Proxy(data, {
get(target, key) {
if(!activeFun) return target[key]
activeFun();
return target[key]
}
set(target, key, newVal) {
if( activeFun ) activeFun();
target[key] = newVal
return true
}
})
let activeFun;
let fun = new weakMap()
const obj = new Proxy(data, {
get(target, key) {
if(!activeFun) return target[key]
let depMap = fun.get(target)
if (!depMap) {
fun.set(target, new Map())
depMap = fun.get(target)
}
let depSet = depMap.get(key)
if (!depSet) {
depMap.set(key, new Set())
depSet = depMap.get(key)
}
depSet.set(activeFun)
return target[key]
}
set(target, key, newVal) {
target[key] = newVal
const depMap = fun.get(target)
if (!depMap) return
const depSet = depMap.get(key)
depSet && depSet.forEach(fun => fun())
return true
}
})