computed函数,是用来定义计算属性的,计算属性不能修改

         应用场景:基于已有的数据,计算一种数据

(1)基本使用:只读

<template>
  <div>
    <div>计算属性</div>
    <button>点击</button>
    <div>今年:{{age}}岁了</div>
    <div>明年:{{nextAge}}岁了</div>
  </div>
  
</templat>

<scirpt>
import {ref,computed} from 'vue'
excort default {
   name:"App",
   setup(){
    const age=ref(18)
    const nextAge=computed(()=>{
     // 回调函数必须return,结果就是计算的结果
    // 如果计算属性依赖的数据发生变化,那么会重新计算
    return  age.value+=1
    })
  retuen { age , nextAge}
    
 }

}
</scirpt>

总结:Vue3zhong计算属性也是组合API风格

需注意的点:

1、回调函数必须return,结果就是计算的结果

2、如果计算属性依赖的数据发生变化,那么会根据依赖的数据项重新计算

3、不要计算属性中进行异步操作,因为异步的结构不可以通过返回值返回

(2)高级使用:可读可写

<template>
  <div>
    <div>计算属性</div>
    <button @click="nextAge=25">修改计算属性</button>
    <div>今年:{{age}}岁了</div>
    <div>明年:{{nextAge}}岁了</div>
  </div>
  
</templat>

<scirpt>
import {ref,computed} from 'vue'
excort default {
   name:"App",
   setup(){
    const age=ref(18)
    const nextAge=computed({
    get(){
    // 读取计算属性的值,调用get方法
    return age.value+1
    },
    set(v){
    // 修改计算属性的值,调用set方法
     age.value=v-1 
    }
    })
  retuen { age , nextAge}
    
 }

总结:

1、计算属性可以直接读取或者修改

2、如果要实现计算属性的修改操作,那么computed的实参应该是对象

      读取数据触发get方法

     修改数据触发set方法,set函数的形参就是你要赋给它的值

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐