vue3 computed

2024-01-03  本文已影响0人  糖醋里脊120625

computed函数接收一个计算函数作为参数,并返回一个响应式的ref对象

1.computed的get和set函数

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: '学习Vue3', done: false },
    { id: 2, text: '学习React', done: false },
    { id: 3, text: '学习Angular', done: true }
  ]
})

const totalTodos = computed(() => {
  return state.todos.length
})

const completedTodos = computed(() => {
  return state.todos.filter(todo => todo.done).length
})

上一篇下一篇

猜你喜欢

热点阅读