响应式原理
- defineProperty API(Vue2实现响应式的原理)
- 针对属性监听,不能监听数组,实际上能监听到数组下标变化,但由于性能代价较大被放弃。
let getDouble = n=>n*2
let obj ={}
let count = 1
let doubule = getDouble(count)
Object.defineProperty(obj,'count',{
get(){
return count
}
set(val){
count = val
double =getDouble(val)
}
})
console.log(double) // 2
obj.count = 2
console.log(double) // 4
// 删除obj.count属性,set函数不会执行,所以还需要$delete一个专门的函数去删除数据
delete obj.count
console.log(double) // 4
- Proxy (Vue3实现响应式的原理)
- 针对对象监听,可以代理更多丰富的数据结构,也能对删除操作进行代理。
// 利用对象的set和get实现
let getDouble = n=>n*2
let obj ={}
let count = 1
let doubule = getDouble(count)
let proxy = new Proxy(obj,{
get(target,prop){
return target[prop]
},
set(target,prop,value){
target[prop] = value;
if(prop==='count'){
double = getDouble(value)
}
},
deleteProperty(target,prop){
delete target[prop]
if(prop==='count'){
double = NaN
}
}
})
console.log(obj.count,double)
proxy.count = 2
console.log(obj.count,double)
delete proxy.count
// 删除属性后
console.log(obj.count,double)
- proxy reactive:把一个对象变成响应式数据,而reactive就是基于Proxy实现的。我们还可以通过watchEffect,在obj.count修改后打印数据
improt {reactive,computed,watchEffect} from 'vue'
let obj = reactive({
conut :1
})
let double =computed(()=>obj.count*2)
obj.count = 2
watchEffect(()=>{
console.log('数据被修改',obj.count,double.value)
})
- Proxy API:只能拦截某一个属性的修改(value setter)。
let getDouble = n=>n*2
let _value = 1
double = getDouble(_value)
let count ={
get value(){
return _value
},
set value(val){
_value =val
double = getDouble(_value)
}
console.log(count.value,double)
count.value = 2
console.log(count.value,double)
}