Implement shallowReactive and Reactive
Let reactiveHandle = {get(target,prop){if(prop === '_is_reactive') return true console.log(' get method ',prop) const result = Reflect.get(target,prop) return result }, // Set (target,prop,value){console.log(' changed set',prop,value) const result = reflect. set(target,prop,value) return result }, DeleteProperty (target,prop){console.log(' deleted data ',target,prop) const result = Reflect.deleteproperty (target,prop) return result}} Function shallowReactive(target){if(target && typeof target === 'object'){ return new Proxy(target,reactiveHandle) } 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,reactiveHandle) } return target }Copy the code
console.log('=====================')
ShallowReadonly read-only
let readonlyHandler ={ get(target,prop){ if(prop === '_is_readonly') return true const result = Reflect.get(target,prop) Console. log(' read get data ',prop,result) return result}, set(target,prop,value){console.warn(' cannot change data, Return true}, deleteProperty(target,prop){console.error(' Cannot delete, //shallowReadonly function shallowReadonly(target){if(target&&) typeof target === 'object'){ return new Proxy(target,readonlyHandler) } return target }Copy the code
Readonly read-only
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
}
Copy the code
console.log('==============')
ShallowRef and ref
shallowRef
function shallowRef(target){ return { _value : Target, get value(){console.log('get data ') return this._value}, Set value(val){console.log('set modifies data ',val) this._value = val}}}Copy the code
ref
function ref(target){ target = reactive(target) return { _is_ref:true, _value : Target, get value(){console.log('get data ') return this._value}, Set value(val){console.log('set modifies data ',val) this._value = val}}}Copy the code
console.log('===============')
IsRef and isReadonly and isProxy and isReactive
function isRef(obj){
return obj && obj._is_ref
}
function isReactive(obj){
return obj && obj._is_reactive
}
function isReadonly(obj){
return obj && obj._is_readonly
}
function isProxy(obj){
return isReactive(obj) || isReadonly(obj)
}
Copy the code