需要引入才能使用
有两种形式,简写形式(只读)和完整形式(可读可写)
1. 简写形式 computed(callback)
只读
<template>
<div class="App">
<p>姓甚:<input type="text" v-model="chicken.firstName" /></p>
<p>名甚:<input type="text" v-model="chicken.lastName" /></p>
<p v-show="fullNmae">全名是:{
{ fullNmae }}</p>
</div>
</template>
<script>
import { computed, reactive } from 'vue'
export default {
name: 'App',
setup() {
const chicken = reactive({
firstName: '坤',
lastName: '坤',
})
// 计算属性 computed() 中传入一个回调函数,这个是简写形式,只读的
let fullNmae = computed(() => chicken.firstName + '-' + chicken.lastName)
return { chicken, fullNmae }
},
}
</script>
2. 完整(对象)形式 computed({ get() { ... },set() { ... } })
可读可写
<template>
<div class="App">
<p>姓甚:<input type="text" v-model="chicken.firstName" /></p>
<p>名甚:<input type="text" v-model="chicken.lastName" /></p>
<p v-show="fullNmae">全名是:{
{ fullNmae }}</p>
<p>全名是:<input type="text" v-model="fullNmae" /></p>
</div>
</template>
<script>
import { computed, reactive } from 'vue'
export default {
name: 'App',
setup() {
const chicken = reactive({
firstName: '坤',
lastName: '坤',
})
// 计算属性
let fullNmae = computed({
get() {
return chicken.firstName + '-' + chicken.lastName
},
set(val) {
let arr = val.split('-')
chicken.firstName = arr[0]
chicken.lastName = arr[1]
},
})
return { chicken, fullNmae }
},
}
</script>
原文链接:https://blog.csdn.net/qq_52845451/article/details/126671709
此处评论已关闭