1.shallowReactive与reactive
//shallowReactive(浅的监视)与reative
//定义一个reactiveHandler处理对象
const reactiveHandler = {
get(target,prop){
if(prop === '_is_reactive'){
return true
}
const result = Reflect.get(target,prop)
console.log("拦截到了读",prop)
return result
},
set(target,prop,value){
const result = Reflect.set(target,prop,value)
console.log("拦截到了添加与修改",prop,value)
return result
},
deleteProperty(target,prop){
const result = Reflect.deleteProperty(target,prop)
console.log("拦截到了删除",prop)
return result
}
}
function shallowReactive(target){
//判断输入数据的类型是否为object
if(target&&typeof target === 'object'){
return new Proxy(target,reactiveHandler)
}
//否则为基本数据类型,直接返回
return target
}
function reactive(target){
if(target&&typeof target === 'object'){
if(Array.isArray(target)){
target.forEach((item,index)=>{
target[index] = reactive(item)
})
}else{
Object.keys(target).forEach(key=>{
target[key] = reactive(target[key])
})
}
return new Proxy(target,reactiveHandler)
}
return target
}
2.shallowReadonly与readonly函数
const readonlyHandler = {
get(target,prop){
if(prop === '_is_readonly'){
return true
}
const result = Reflect.get(target,prop)
console.log("拦截到了读取数据",prop,result)
return result
},
set(target,prop){
console.warn("只能读取数据,不能删改")
return true
},
deleteProperty(target,prop){
console.warn("只能读取数据,不能删改")
return true
}
}
//手写shallowReadonly与readonly
function shallowReadonly(target){
if(target && typeof target === 'object'){
return new Proxy(target,readonlyHandler)
}
return target
}
function readonly(target){
if(target && typeof target === 'object'){
if(Array.isArray(target)){
target.forEach((item,index)=>{
target[index] = readonly(item)
})
}else{
Object.keys(target).forEach(key =>{
target[key] = readonly(target[key])
})
}
return new Proxy(target,readonlyHandler)
}
return target
}
3.shallowRef和ref函数
//定义一个shallowRef
function shallowRef(target){
return{
//保存target数据
_value:target,
get value(){
console.log("劫持到了读取数据")
return this._value
},
set value(val){
console.log("劫持到了修改数据,准备更新界面")
this._value = val
}
}
}
//定义一个ref函数
function ref(target){
target = reactive(target)
return{
_is_ref:true,
//保存target数据
_value:target,
get value(){
console.log("劫持到了读取数据")
return this._value
},
set value(val){
console.log("劫持到了修改数据,准备更新界面")
this._value = val
}
}
}
4.isRef,isReactive与isReadonly以及isProxy
//定义一个函数isRef,判断当前的对象是不是ref对象
function isRef(obj){
return obj && obj._is_ref
}
//定义一个函数isReadonly,判断当前对象是不是readonly对象
function isReadonly(obj){
return obj && obj._is_readonly
}
//定义一个函数isReactive,判断当前对象是不是reactive对象
function isReactive(obj){
return obj && obj._is_reactive
}
//定义一个函数isProxy,判断当前对象是不是reactive对象或者readonly对象
function isProxy(obj){
return isReactive(obj) || isReadonly(obj)
}