vue3 简易实现proxy代理
1.基础数据
const state = reactive({ name: 'cld', age: 26, like: 'paint' });
console.log("获取更改age前的值", state.age);
state.age = 28;
console.log("获取更改age后的值", state.age);
核心逻辑 reactive
export function reactive (target) {
return createReactiveObject(target, {
get (target, key, receiver) {
const res = Reflect.get(target, key, receiver);
console.log('用户取值', target, key);
return res;
},
set (target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver);
console.log('用户设置值', target, key);
return res;
}
});
}
const isObject = (obj) => { return typeof obj == 'object' && obj != null; };
function createReactiveObject (target, baseHandler) {
if (!isObject(target)) {
return target;
}
const observed = new Proxy(target, baseHandler);
return observed;
}
const res = Reflect.get(target, key, receiver);
const res = Reflect.set(target, key, value, receiver);
代理实现效果
vue3取值的时候才走代理操作,不取值的时候,不需要深度遍历代理, vue2一开始就深度递归
当数据里为数组或对象的情况下,需要递归代理
get (target, key, receiver) {
const res = Reflect.get(target, key, receiver);
if (isObject(res)) {
return reactive(res);
}
return res;
};
修改值的时候,具体是新增操作还是修改操作 可以定位
set (target, key, value, receiver) {
const hasKey = hasOwn(target, key);
const oldValue = target[key];
const res = Reflect.set(target, key, value, receiver);
if (!hasKey) {
console.log('用户新增值', target, key);
} else if (value !== oldValue) {
console.log('用户修改值', target, key);
}
return res;
};
push数据的时候,会先取arr的push属性,然后取array的length属性 设置值的时候 key是index索引,在该索引上增加值 其实在该索引上增加值之后,还会再次触发set 应该数组的长度改变了 为了减少多余的无必要的操作,可以通过判断不执行任何操作
|