目标
it('isRef', () => {
const a = ref(1);
const user = reactive({ age: 1 });
expect(isRef(a)).toBe(true);
expect(isRef(1)).toBe(false);
expect(isRef(user)).toBe(false);
});
it('unRef', () => {
const a = ref(1);
expect(unRef(a)).toBe(1);
expect(unRef(1)).toBe(1);
});
isRef 实现
使用一个 __v_isRef
的 flag
class RefImpl {
private _value: any;
private _rawValue: any;
// 是不是 ref 的标识
public __v_isRef = true;
public dep;
constructor(value) {
this._rawValue = value;
this._value = convert(value);
this.dep = new Set();
}
get value() {
trackRefValue(this);
return this._value;
}
set value(newValue) {
if (hasChange(newValue, this._rawValue)) {
this._rawValue = newValue;
this._value = convert(newValue);
triggerEffect(this.dep);
}
}
}
export function isRef(ref) {
return !!ref.__v_isRef;
}
unRef 实现
export funciton unRef(ref) {
// 看看是不是 ref,是就返回 ref.value,否则直接返回 ref
return isRef(ref) ? ref.value : ref;
}