当 computed 内部的变量发生了变化,computed 会重新计算,并返回新的值。

函数式写法

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 可以通过模板语法直接使用 -->
<template>
<div>{{ sum }}</div>
</template>
<script>
export default { 
computed:{
sum(){
return this.num1 + this.num2
}
}
}
</script>

setup 写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 可以通过模板语法直接使用 -->
<template>
<div>{{ sum }}</div>
</template>
<script>
export default { 
setup(){  
const num1 = ref(1)  
const num2 = ref(1)  
let sum = computed(()=>{ 
return num1.value + num2.value  
}) 
return {
sum
}
}
}
</script>

options 写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 可以通过模板语法直接使用 -->
<template>
<div>{{ sum }}</div>
</template>
<script>
export default { 
computed:{ 
sum:{  
get(){
return this.num1 * this.num2
},
set(value){
this.num1 = value / 2
this.num2 = value / 3

}
}
}
</script>