Vue3.0 - computed函数
前言
computed
计算属性,与普通JS
函数相比computed
性能更好,以为它存在计算缓存,js
函数没有,其计算结果是只读的,可通过set
方法修改。
computed的基本用法
<body>
<div id="app">
<input v-model="firstName" type="number"/>
<input v-model="lastName" type="number"/>
<div>{{fullName}}</div>
</div>
</body>
<script>
const {createApp, ref, computed} = Vue;
const firstName = ref(1);
const lastName = ref(2);
const app = {
// 入口函数
setup() {
// 基础用法
let fullName = computed(() => firstName.value + lastName.value)
// console.log(fullName ++) // error computed 是只读的
return {
firstName,
lastName,
fullName
}
}
}
// 挂载(建立vue与dom的联系)
createApp(app).mount('#app')
</script>
computed的set和get方法
<body>
<div id="app">
<input v-model="firstName" type="number"/>
<input v-model="lastName" type="number"/>
<div>{{fullNames}}</div>
</div>
</body>
<script>
const {createApp, ref, computed} = Vue;
const firstName = ref(1);
const lastName = ref(2);
const app = {
// 入口函数
setup() {
// get set 方法
const fullNames = computed({
get: () => firstName.value + lastName.value,
set: (val) => {
firstName.value = val
}
})
fullNames.value = 7 // set
return {
firstName,
lastName,
fullNames
}
}
}
// 挂载(建立vue与dom的联系)
createApp(app).mount('#app')
</script>
![](https://img-blog.csdnimg.cn/d1b51b924c4d4ea88f8fecaa32708d63.jpg)