let mul = computed({
get:()=>{
return num1.value *10
set:(value)=>{
return num1.value = value/10
这两种写法不太一样,仔细观察区别不大,get 和 set 调用也是一样的。
在此示例中代码简单,如果没太理解,可查看文章后面的完整实例2。
完整实例1:
<template>
{{num1}} + {{num2}} = {{sum}}
<button @click="num1++">num1自加</button>
<button @click="num2++">num2自加</button>
</template>
<script>
import { ref, computed } from "vue"
export default{
setup(){
const num1 = ref(1)
const num2 = ref(1)
let sum = computed(()=>{
return num1.value + num2.value
return{
num1,
num2,
</script>
完整实例2:
<template>
{{num1}} + {{num2}} = {{sum}}<br>
<button @click="num1++">num1自加</button>
<button @click="num2++">num2自加</button>
{{num1}} * 10 = {{mul}}
<button @click="mul=100">改值</button>
</template>
<script>
import { ref, computed } from "vue"
export default{
setup(){
const num1 = ref(1)
const num2 = ref(1)
let sum = computed(()=>{
return num1.value + num2.value
let mul = computed({
get:()=>{
return num1.value *10
set:(value)=>{
return num1.value = value/10
return{
num1,
num2,
</script>
三、computed 传参
计算属性需要传入一个参数怎么写呢?
<template>
<div v-for="(item,index) in arr" :key="index" @click="sltEle(index)">
{{item}}
</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。
解决办法:
需要在计算属性 内部返回一个函数。修改代码如下:
const sltEle = computed( ()=>{
return function(index){
console.log('index',index);
好了小编今天的文章就到此结束了,喜欢我的可以点个关注哦!