1、shallowReadonly
const shallowReadonlyHandler = {
get(target,prop){
console.log('执行了数据的获取操作');
return Reflect.get(target,prop);
},
set(target,prop,val){
console.warn('只读数据不能进行更改或添加操作');
return true;
},
deleteProperty(target,prop){
console.warn('只读数据不能进行删除操作');
return true;
}
}
const shallowReadonly = (target) => {
if(target && typeof target === 'object'){
return new Proxy(target,shallowReadonlyHandler);
}
return target;
}
const user = shallowReadonly({
name:'Agwnebi',
age:25,
car:{
name:'宝马',
color:'blue'
}
})
console.log(user.name);
user.age = 26;
console.log(user);
2、readonly
const readonlyHandler = {
get(target,prop){
console.log('执行了数据的读取操作');
return Reflect.get(target,prop);
},
set(target,prop,val){
console.warn('只读数据不能进行更改或添加操作');
return true;
},
deleteProperty(target,prop){
console.warn('只读数据不能进行删除操作');
return true;
}
}
const 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;
}
const user = readonly({
name:'Agwnebi',
age:25,
car:{
name:'宝马',
color:'blue'
}
})
console.log(user.name);
user.age = 26;
console.log(user);