美文网首页
vue3 computed

vue3 computed

作者: 糖醋里脊120625 | 来源:发表于2024-01-03 15:06 被阅读0次

    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
    })
    
    

    相关文章

      网友评论

          本文标题:vue3 computed

          本文链接:https://www.haomeiwen.com/subject/lyamndtx.html