目标

  1. it('isRef', () => {
  2. const a = ref(1);
  3. const user = reactive({ age: 1 });
  4. expect(isRef(a)).toBe(true);
  5. expect(isRef(1)).toBe(false);
  6. expect(isRef(user)).toBe(false);
  7. });
  8. it('unRef', () => {
  9. const a = ref(1);
  10. expect(unRef(a)).toBe(1);
  11. expect(unRef(1)).toBe(1);
  12. });

isRef 实现

使用一个 __v_isRef的 flag

  1. class RefImpl {
  2. private _value: any;
  3. private _rawValue: any;
  4. // 是不是 ref 的标识
  5. public __v_isRef = true;
  6. public dep;
  7. constructor(value) {
  8. this._rawValue = value;
  9. this._value = convert(value);
  10. this.dep = new Set();
  11. }
  12. get value() {
  13. trackRefValue(this);
  14. return this._value;
  15. }
  16. set value(newValue) {
  17. if (hasChange(newValue, this._rawValue)) {
  18. this._rawValue = newValue;
  19. this._value = convert(newValue);
  20. triggerEffect(this.dep);
  21. }
  22. }
  23. }
  24. export function isRef(ref) {
  25. return !!ref.__v_isRef;
  26. }

unRef 实现

  1. export funciton unRef(ref) {
  2. // 看看是不是 ref,是就返回 ref.value,否则直接返回 ref
  3. return isRef(ref) ? ref.value : ref;
  4. }