function ref(val) {
const wrapper = { value: val };
// 不可枚举
Object.defineProperty(wrapper, "__v_isRef", {
value: true,
});
return reactive(wrapper);
}
const obj = reactive({ foo: 1, bar: 2 });
const newObj = {
foo: {
get value() {
return obj.foo;
},
},
bar: {
get value() {
return obj.bar;
},
},
};
function toRef(obj, key) {
const wrapper = {
get value() {
return obj[key];
},
set value(val) {
obj[key] = val;
},
};
return wrapper;
}
function toRefs(obj) {
let ret = {};
for (const key in obj) {
ret[key] = toRef(obj, key);
}
}
function proxyRefs(target) {
return new Proxy(target, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
return value.__v_isRef ? value.value : value;
},
set(target, key, newVal, receiver) {
const value = target[key];
if (value.__v_isRef) {
value.value = newVal;
return;
}
return Reflect.set(target, key, newVal, receiver);
},
});
}