Skip to content

Latest commit

 

History

History
75 lines (66 loc) · 1.18 KB

第6章.md

File metadata and controls

75 lines (66 loc) · 1.18 KB

ref 定义

function ref(val) {
  const wrapper = { value: val };

  // 不可枚举
  Object.defineProperty(wrapper, "__v_isRef", {
    value: true,
  });
  return reactive(wrapper);
}

reactive 解构就失去响应了,先手动解决

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);
  }
}

自动脱 ref

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);
    },
  });
}