一、完整代码
<template>
<div class="about">
<h1>Computed的用法</h1>
<h3>姓:{{ person.firstName }}</h3>
<input type="text" v-model="person.firstName">
<h3>名:{{ person.lastName }}</h3>
<input type="text" v-model="person.lastName">
<div v-if="person.fullName">
<h3>全名:{{ person.fullName }}</h3>
<input type="text" v-model="person.fullName">
</div>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
name:'aboutPage',
setup() {
let person = reactive({
firstName: '张',
lastName: '三'
})
person.fullName = computed({
get() {
return person.firstName + '-' + person.lastName
},
set(value) {
const nameArr = value.split('-')
person.firstName = nameArr[0]
person.lastName = nameArr[1]
}
})
return {
person
}
}
}
</script>
二、主要代码
get:访问了这个属性
set:修改这个属性时操作的业务逻辑
person.fullName = computed({
get() {
return person.firstName + '-' + person.lastName
},
set(value) {
const nameArr = value.split('-')
person.firstName = nameArr[0]
person.lastName = nameArr[1]
}
})