computed函數(shù)接收一個計算函數(shù)作為參數(shù),并返回一個響應(yīng)式的ref對象
1.computed的get和set函數(shù)
const state = reactive({
count: 2
})
const doubleCount = computed({
get() {
return state.count * 2
},
set(value) {
state.count = value / 2
}
})
console.log(doubleCount.value) // 輸出:0
doubleCount.value = 6
console.log(state.count) // 輸出:3
console.log(doubleCount.value) // 輸出:6
**************************************************************************
2.computed的基本用法
const state = reactive({
todos: [
{ id: 1, text: '學(xué)習(xí)Vue3', done: false },
{ id: 2, text: '學(xué)習(xí)React', done: false },
{ id: 3, text: '學(xué)習(xí)Angular', done: true }
]
})
const totalTodos = computed(() => {
return state.todos.length
})
const completedTodos = computed(() => {
return state.todos.filter(todo => todo.done).length
})