写在前面
好呀朋友们,又见面啦,今天讲vue3里的computed函数。
1.基本使用:只读
computed函数,是用来定义计算属性的,计算属性不能修改。
<template>
<div>
<div>计算属性</div>
<hr>
<button @click='age=25'>点击</button>
<div>今年:{{age}}岁了</div>
<div>明年:{{nextAge}}岁了</div>
</div>
</template>
<script>
import { ref, computed } from 'vue'
export default {
name: 'App',
setup () {
// 计算属性:简化模板
// 应用场景:基于已有的数据,计算一种数据
const age = ref(18)
// 计算属性基本使用
const nextAge = computed(() => {
// 回调函数必须return,结果就是计算的结果
// 如果计算属性依赖的数据发生变化,那么会重新计算
return age.value + 1
})
return { age, nextAge }
}
}
</script>
<style lang="less">
</style>
战术总结:Vue3中计算属性也是组合API风格
-
回调函数必须return,结果就是计算的结果
-
如果计算属性依赖的数据发生变化,那么会重新计算
-
不要在计算中中进行异步操作
高级写法:可读可写
<template>
<div>
<div>计算属性</div>
<hr>
<button @click='age=25'>点击</button>
<button @click='nextAge=28'>点击修改</button>
<div>今年:{{age}}岁了</div>
<div>明年:{{nextAge}}岁了</div>
</div>
</template>
<script>
import { ref, computed } from 'vue'
export default {
name: 'App',
setup () {
// 计算属性:简化模板
// 应用场景:基于已有的数据,计算一种数据
const age = ref(18)
// // 计算属性基本使用
// const nextAge = computed(() => {
// // 回调函数必须return,结果就是计算的结果
// // 如果计算属性依赖的数据发生变化,那么会重新计算
// return age.value + 1
// })
// 修改计算属性的值
const nextAge = computed({
get () {
// 如果读取计算属性的值,默认调用get方法
return age.value + 1
},
set (v) {
// 如果要想修改计算属性的值,默认调用set方法
age.value = v - 1
}
})
return { age, nextAge }
}
}
</script>
<style lang="less">
</style>
战术总结
1、计算属性可以直接读取或者修改
2、如果要实现计算属性的修改操作,那么computed的实参应该是对象
2.1、读取数据触发get方法
2.1、修改数据触发set方法,set函数的形参就是你赋给他的值。
写在最后
以上就是今天的所有内容啦,要是有没讲清楚的点欢迎向我提问~