计算属性
栗子
<script setup lang='ts'>
import { computed, reactive } from "vue";
const author = reactive({
name: "John Doe",
books: [
"Vue 2 - Advanced Guide",
"Vue 3 - Basic Guide",
"Vue 4 - The Mystery",
],
});
const publishedBooksMessage = computed<string>(() => {
return author.books.length > 0 ? "Yes" : "No";
});
</script>
<template>
<h2>Demo 01</h2>
<p>Has published books:</p>
<span>{{ publishedBooksMessage }}</span>
</template>
定义一个计算属性publishedBooksMessage。 computed()方法期望接收一个getter函数,返回值为一个计算属性ref,计算属性的ref会在模板中自动解包,在模板表达式中引用时无需添加*.value*。
计算属性会自动追踪响应式依赖。同步更新。
计算属性标注类型
const test = computed<number>(() => {
})
计算属性缓存与方法的区别: 模板表达式中可以直接调用一个函数来获取与计算属性相同的结果:
<p>{{ calculateBooksMessage() }}</p>
不同之处:
- 计算属性值会基于其响应式依赖被缓存(意思就是只要以依赖的值没有改变计算属性就不会重复执行getter函数)。
- 方法(calculateBooksMessage)总是会在重新渲染发生时再次执行
为什么需要缓存呢?
当我们有一个非常消耗性能的计算属性list,需要循环一个巨大的数组并做许多的计算逻辑,其中可能还会有其他的计算属性依赖于list,没有缓存的情况下会重复执行多次的list的getter
可写的计算属性
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
// getter
get() {
return firstName.value + ' ' + lastName.value
},
// setter
set(newValue) {
// 注意:我们这里使用的是解构赋值语法
[firstName.value, lastName.value] = newValue.split(' ')
}
})
</script>