computed

231 阅读1分钟

1、接受一个getter函数

setup() {
  const count = ref(1);
  // 接受一个 getter 函数,并根据 getter 的返回值返回一个不可变的响应式 ref 对象。
  const dobuleCount = computed(() => count.value * 2);

  console.log(isRef(dobuleCount), dobuleCount.value); // true 2
  
  dobuleCount.value++; // error 没有set函数,readonly 不可变
}

2、接受一个具有 get 和 set 函数的对象

setup() {
  const count = ref(1);

  // 或者是接受一个具有 get 和 set 函数的对象,用来创建可写的 ref 对象。
  const computedCount = computed({
    get: () => {
      return count.value;
    },
    set: val => {
      count.value = val;
    }
  });
  computedCount.value = 2;
  console.log(count.value); // 2
}