Vue3 中 Computed 用法

Computed 又被称作计算属性,用于动态的根据某个值或某些值的变化,来产生对应的变化,computed 具有缓存性,当无关值变化时,不会引起 computed 声明值的变化。 产生一个新的变量并挂载到 vue 实例上去。

vue3 中 的 computed 的使用,由于 vue3 兼容 vue2 的选项式 API,所以可以直接使用 vue2 的写法,以下是 vue3 中 computed 的写法和 vue2 中的写法的对比。

组合式 API 中使用 computed 时,需要先引入:import { computed } from "vue"。 引入之后 computed 可以传入的参数有两种: 回调函数和 options 。 具体使用

一、函数式写法

在 vue2 中,computed 写法:

javascript 复制代码
computed:{  
  sum(){  
    return this.num1+ this.num2  
  } 
}

在 vue3 如果使用选项式 API 也可以这样写,主要看下组合式 API 的使用。

示例 1:求和

javascript 复制代码
import { ref, computed }  from "vue"

export default { 
  setup(){  
    const num1 = ref(1)  
    const num2 = ref(1)  
    let sum = computed(()=>{  
      return num1.value + num2.value   
    }) 
  }
}

调用 computed 时, 传入了一个箭头函数,返回值作为 sum 。相比之前,使用更加简单了。如果需要计算多个属性值,直接调用就可以。如:

javascript 复制代码
let sum = computed(()=>{
  return num1.value + num2.value 
})
let mul = computed(()=>{  
  return num1.value * num2.value  
})

二、options 写法

计算属性默认只有 getter ,在需要的时候也可以提供 setter 。在 vue2 中用法如下:

javascript 复制代码
computed:{ 
 mul:{  
  get(){ // num1 值改变时触发    
    return this.num1 * 10   
  },  
  set(value){ // mul 值被改变时触发    
    this.num1 = value /10   
  }  
 } 
}

mul 属性是给 num1 放大 10,如果修改 mul 的值,则 num1 也随之改变。

在 vue3 中 :

javascript 复制代码
let mul = computed({ 
  get:()=>{   
    return num1.value *10 
  }, 
  set:(value)=>{   
    num1.value = value/10 
  } 
})

这两种写法不太一样,仔细观察区别不大,get 和 set 调用也是一样的。

三、computed 传参

计算属性需要传入一个参数怎么写呢?

javascript 复制代码
<template> 
  <div>  
    <div v-for="(item,index) in arr" :key="index" @click="sltEle(index)">    
      {{item}}   
    </div>
  </div>
</template>
<script>
import { ref, computed,reactive } from "vue"

export default{ 
  setup(){   
    const arr = reactive([    '哈哈','嘿嘿'   ])  
    const sltEle = computed( (index)=>{   
      console.log('index',index);   
    })  
    return{ arr,sltEle }
  } 
}
</script>

直接这样写,运行的时候,出现错误:Uncaught TypeError: $setup.sltEle is not a function。

原因:

computed 计算属性并没有给定返回值,我们调用的是一个函数,而 computed 内部返回的并不是一个函数,所以就会报错:sltEle is not a function。

解决办法:

需要在计算属性 内部返回一个函数。修改代码如下:

javascript 复制代码
const sltEle = computed(()=>{ 
  return function(index) {  
    console.log('index',index);
  } 
}
相关推荐
大橙子额4 分钟前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
WooaiJava1 小时前
AI 智能助手项目面试技术要点总结(前端部分)
javascript·大模型·html5
LYFlied1 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a2 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
Never_Satisfied2 小时前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
董世昌412 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
B站_计算机毕业设计之家2 小时前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
WeiXiao_Hyy2 小时前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
吃杠碰小鸡3 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone3 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word