ref & unref & isRef

1,280 阅读1分钟
function getValue(data: any) {
  // isRef 检查值是否为一个 ref 对象。
  if (isRef(data)) {
    return data.value;
  }
  return data;
}

function getValue2(data: any) {
  // unref 如果参数是一个 ref,则返回内部值,否则返回参数本身。这是 val = isRef(val) ? val.value : val 的语法糖函数。
  return unref(data);
}

export default {
  name: 'Count',
  setup() {
    // 接受一个内部值并返回一个响应式且可变的 ref 对象。ref 对象具有指向内部值的单个 property .value。
    const refObj = ref({ count: 1 });
    refObj.value.count++;

    // 有时我们可能需要为 ref 的内部值指定复杂类型。想要简洁地做到这一点,我们可以在调用 ref 覆盖默认推断时传递一个泛型参数:
    const refCount = ref<string | number>(1);
    refCount.value = 'string'; // ok

    console.log(getValue(ref(1)) === getValue2(1)); // true

    return { refObj };
  }
};