Vue3中的计算属性变成了一个组合式API
使用方法:
引入computed:
import {reactive,computed} from 'vue'
使用方式:
//计算属性简写方式(计算属性不可被修改)
obj.fullNum = computed(()=>{
return obj.firstName + '-' +obj.lateName
);
//计算属性完整写法(可读写)
obj.fullNum = computed({
get(){
return obj.firstName + '-' + obj.lateName
},
set(value){
const nameArr = value.split('-')
obj.firstName = nameArr[0]
obj.lateName = nameArr[1]
}
});
完整代码示例:
<template>
<div class="hello">
<h1>计算属性</h1>
姓:<input type="text" v-model="obj.firstName">
<br>
名:<input type="text" v-model="obj.lateName">
<h2>合计:{{obj.fullNum}}</h2>
合计:<input type="text" v-model="obj.fullNum">
</div>
</template>
<script>
import {reactive,computed} from 'vue'
export default {
name: 'Home',
setup() {
let obj = reactive({
firstName:'1',
lateName:'2',
})
//计算属性简写方式(计算属性不可被修改)
obj.fullNum = computed(()=>{
return obj.firstName + '-' +obj.lateName
});
//计算属性完整写法(可读写)
obj.fullNum = computed({
get(){
return obj.firstName + '-' + obj.lateName
},
set(value){
const nameArr = value.split('-')
obj.firstName = nameArr[0]
obj.lateName = nameArr[1]
}
});
return {
obj,
}
},
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
效果图:
以上就是vue3中计算属性的使用方式。