Vue3的计算函数
文章目录计算属性的简写计算属性的完整写法Vue3中的计算属性有两种写法:简写和完整写法。下面一一介绍下。计算属性的简写main.jsimport { createApp } from 'vue'import App from './App.vue'createApp(App).mount('#app')App.vue<template><Demo/></templat
·
Vue3中的计算函数有两种写法:简写和完整写法。下面一一介绍下。
计算函数的简写
- main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
- App.vue
<template>
<Demo/>
</template>
<script>
import Demo from './components/Demo.vue'
export default {
name: 'App',
components: {
Demo
}
}
</script>
- Demo.vue
<template>
姓:<input type="text" v-model="person.firstName">
<br>
名:<input type="text" v-model="person.lastName">
<div>全名:{{fullName}}</div>
</template>
<script>
import {reactive,computed} from "vue";
export default {
name: 'Demo',
setup(){
let person = reactive({
firstName:"张",
lastName:"三"
})
let fullName = computed(() => {
return person.firstName + "-" + person.lastName;
})
return {
person,
fullName
}
}
}
</script>
- 启动应用,测试效果
其实,fullName
也是应该是person
的属性,所以修改Demo.vue,稍稍改进下。
<template>
姓:<input type="text" v-model="person.firstName">
<br>
名:<input type="text" v-model="person.lastName">
<div>全名:{{person.fullName}}</div>
</template>
<script>
import {reactive,computed} from "vue";
export default {
name: 'Demo',
setup(){
let person = reactive({
firstName:"张",
lastName:"三"
})
person.fullName = computed(() => {
return person.firstName + "-" + person.lastName;
})
return {
person
}
}
}
</script>
计算函数的完整写法
- main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
- App.vue
<template>
<Demo/>
</template>
<script>
import Demo from './components/Demo.vue'
export default {
name: 'App',
components: {
Demo
}
}
</script>
- Demo.vue
<template>
姓:<input type="text" v-model="person.firstName">
<br>
名:<input type="text" v-model="person.lastName">
<br>
姓名:<input type="text" v-model="person.fullName">
</template>
<script>
import {reactive,computed} from "vue";
export default {
name: 'Demo',
setup(){
let person = reactive({
firstName:"张",
lastName:"三"
})
person.fullName = computed({
get(){
return person.firstName + "-" + person.lastName;
},
set(value){
const tempArr = value.split("-");
person.firstName = tempArr[0];
person.lastName = tempArr[1];
}
})
return {
person
}
}
}
</script>
- 启动应用,测试效果
更多推荐
已为社区贡献19条内容
所有评论(0)