vue3中computed api
vue3
中computed api
有两种用法
- 只读的
computed
- 可写的
computed
只读的computed
computed
传入一个用于返回计算属性的函数
import {computed, ref} from "vue";
const count = ref(0)
const countPlus = computed(() => count.value+1,)
console.log(countPlus.value)
count.value = 10
console.log(countPlus.value)
控制台输出
可写的computed
computed
传入一个保护get和set函数的对象
get
函数用于返回计算属性的值
set
函数用于设置计算属性的值
import {computed, ref} from "vue";
const count = ref(0)
const countPlus = computed({
get: () => count.value+1,
set: (val) => {
count.value = val-1
}
})
countPlus.value = 10 // 等同于 count.value = 9
console.log(countPlus.value)
console.log(count.value)
控制台输出