<template>
<div>案例实战</div>
<hr>
<button @click="age=25">点击</button>
<div>今年{{age}}岁</div>
<div>明年{{nextAge}}岁</div>
</template>
// 引入ref和computed
import { ref, computed } from 'vue'
export default {
name: 'App',
setup () {
// age初始值18
const age = ref(18)
// 使用计算属性修改为明年19岁
const nextAge = computed(() => {
return age.value + 1
})
// 在setup函数中使用后,必须return出去才能在模板中使用
return { age, nextAge }
}
}
计算属性是不能直接修改,因为它是只读的。
computed计算属性中有get(){}和set(){}方法配合修改计算属性,使用它就可以修改计算属性的值了!
这里千万注意:
调用computed的get和set方法时是对象的方式,而不是个回调函数
set方法:
<template>
<div>案例实战</div>
<hr>
<button @click="age=25">点击</button>
<button @click="nextAge=28">修改</button>
<div>今年{{age}}岁</div>
<div>明年{{nextAge}}岁</div>
</template>
import { ref, computed } from 'vue'
export default {
name: 'App',
setup () {
const age = ref(18)
const nextAge = computed({
get () {
// 当我要读取一个计算属性的值时,默认调用的是get方法
return age.value + 1
},
// 形参v就是你传入的值
set (v) {
// 而当我要修改计算属性的值的时候,默认调用的则是set方法
// console.log(v)
age.value = v - 1
}
})
return { age, nextAge }
}
}