一、Vue3计算属性基础使用
1.1. 不使用计算属性
当我们需要针对一些数据进行一些逻辑运算时可以使用模板中的表达式如下:
<script setup lang="ts">
import { reactive } from "vue";
const onePeople = reactive({
name: "Sam Xiaoguai",
chineseName: [
"萨姆",
"小乖"
]
});
</script>
<template>
<div>
{{ onePeople.chineseName.length > 0 ? "有中文名" : "没有" }}
</div>
</template>
<style scoped></style>
但是如果在模板中写太多逻辑,会让模板变得臃肿,难以维护。因此我们可以使用计算属性computed() 方法来描述依赖响应式状态的复杂逻辑,返回值为一个计算属性 ref。
1.2. 使用计算属性
<script setup lang="ts">
import { reactive,computed } from "vue";
const onePeople = reactive({
name: "Sam Xiaoguai",
chineseName: [
"萨姆",
"小乖"
]
});
// 一个计算属性 ref
const haveChineseName = computed<string>(() => {
return onePeople.chineseName.length > 0 ? "有中文名" : "没有"
})
</script>
<template>
<div>
{{ haveChineseName }}
</div>
</template>
<style scoped></style>
二、计算属性VS常规方法
<script setup lang="ts">
import { reactive,computed } from "vue";
const onePeople = reactive({
name: "Sam Xiaoguai",
chineseName: [
"萨姆",
"小乖"
]
});
// 一个计算属性 ref
const haveChineseName = computed<string>(() => {
return onePeople.chineseName.length > 0 ? "有中文名" : "没有"
})
function haveChineseNameFun ():string {
return onePeople.chineseName.length > 0 ? "有中文名" : "没有"
}
</script>
<template>
<div>
<span>{{ haveChineseName }}</span>
<span>{{ haveChineseName }}</span>
<span>{{ haveChineseName }}</span>
<span>{{ haveChineseName }}</span>
</div>
<div>
<span>{{ haveChineseNameFun() }}</span>
<span>{{ haveChineseNameFun() }}</span>
<span>{{ haveChineseNameFun() }}</span>
<span>{{ haveChineseNameFun() }}</span>
</div>
</template>
<style scoped></style>
在模板中,分别使用了方法和计算属性四次,然而,然而,不同之处在于计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。这意味着只要
onePeople不改变,无论多少次访问haveChineseName都会立即返回先前的计算结果,而不用重复执行getter函数。
-
如下:计算属性永远不会更新,因为
Date.now()并不是一个响应式依赖 -
相比之下,方法调用总是会在
重渲染发生时再次执行函数。
<script setup lang="ts">
import { computed } from "vue";
const now = computed<number>(() => Date.now());
function nowTime(): number {
return Date.now();
}
</script>
<template>
<div>
{{ now }}
</div>
<div>
{{ now }}
</div>
<div>
{{ now }}
</div>
<div>
{{ nowTime() }}
</div>
<div>
{{ nowTime() }}
</div>
<div>
{{ nowTime() }}
</div>
</template>
<style scoped></style>
所以当我们有一个非常耗性能的计算属性 list,需要循环一个巨大的数组并做许多计算逻辑,并且可能也有其他计算属性依赖于 list。没有缓存的话,我们会重复执行非常多次 list 的 getter,然而这实际上没有必要!如果你确定不需要缓存,那么也可以使用方法调用
三、可写计算属性
计算属性默认是只读的。当你尝试修改一个计算属性时,你会收到一个运行时警告。
Write operation failed: computed value is readonly
因此如果你需要用到“可写”的属性,你可以通过同时提供 getter 和 setter 来创建
<script setup lang="ts">
import { ref, computed } from 'vue'
const firstName = ref('Sam')
const lastName = ref('xiaoguai')
const fullName = computed({
// getter
get() {
return firstName.value + ' ' + lastName.value
},
// setter
set(newValue) {
// 注意:我们这里使用的是解构赋值语法
[firstName.value, lastName.value] = newValue.split(' ')
}
})
fullName.value = "sam xiaoguai"
</script>
<template>
<div>
{{ fullName }}
</div>
</template>
<style scoped></style>
1084

被折叠的 条评论
为什么被折叠?



