目标
it('nested reactive', () => {
const original = {
nested: {
foo: 1,
},
array: [{ bar: 2 }],
};
const observed = reactive(original);
expect(isReactive(observed.nested)).toBe(true);
expect(isReactive(observed.array)).toBe(true);
expect(isReactive(observed.array[0])).toBe(true);
});
it('nested readonly', () => {
const original = { foo: 1, bar: { baz: 2 } };
const wrapped = readonly(original);
expect(isReadonly(wrapped.bar)).toBe(true);
expect(isReadonly(original.bar)).toBe(false);
});
实现
只需要看看 get 中返回出去的 res 是不是 Object,如果是再次调用 reactive 转换成响应性对象。
同理 readonly,只需要再判断不是 isReadonly,而再次调用 readonly 转换
function createGetter(isReadonly = false) {
return function get(target, key) {
if (key === ReactiveFlags.IS_REACTIVE) {
return !isReadonly;
} else if (key === ReactiveFlags.IS_READONLY) {
return isReadonly;
}
const res = Reflect.get(target, key);
// 判断是不是 Object 可以抽离到公共工具方法
if (isObject(res)) {
return isReadonly ? readonly(res) : reactive(res);
}
if (!isReadonly) {
track(target, key);
}
return res;
};
}
export const isObject = (val) => {
return val !== null && typeof val === 'object';
};