Vue计算属性Computed
30. Vue计算属性Computed
1. 定义
Computed
属性是Vue
中的一个计算属性,是一种基于其它属性值计算而来的属性值,具有缓存机制,在依赖的属性值发生变化时会重新计算。
使用computed
属性可以避免在模板中书写过多的计算逻辑,提高代码可读性和维护性。
下面是一个计算属性的示例:
<template><div><h3>单价: ¥{{ price }}</h3><input type="text" v-model="count" placeholder="请输入数量">个<h3>总价: ¥{{ totalPrice }}</h3></div>
</template>
<!-- vue2 -->
<script>
export default {data() {return {price: 12,count: null}},computed: {totalPrice() {return this.price * this.count}}
}
</script>
<!-- vue3 -->
<script setup>
import { ref, computed } from "vue"
const price = ref(12)
const count = ref(0)
const totalPrice = computed(() => {return price.value * count.value
})
</script>
2. computed和methods对比
计算属性是有缓存的, 当我们多次使用计算属性时, 计算属性中的运算只会执行一次。如下图:
<template><div><div>{{ fullName }}</div><div>{{ fullName }}</div><div>{{ fullName }}</div><div>{{ fullName }}</div><div>{{ fullName }}</div><div>{{ fullName }}</div><div>{{ getFullName() }}</div><div>{{ getFullName() }}</div><div>{{ getFullName() }}</div><div>{{ getFullName() }}</div><div>{{ getFullName() }}</div></div>
</template>
<!-- vue2 -->
<script>
export default {data() {return {firstName: "Jack",lastName: "Ma"}},computed: {fullName() {console.log("computed获取fullname");return this.firstName + this.lastName;}},methods:{getFullName() {console.log("methods获取fullname");return this.firstName * this.lastName;}}
}
</script>
<!-- vue3 -->
<script setup>
import { ref, computed } from "vue"const firstName = ref("J.K.")
const lastName = ref("Rowling")const fullName = computed(() => {console.log("computed获取full");return firstName.value + lastName.value
})const getFullName = function() {console.log("methods获取full");return firstName.value + lastName.value
}
</script>
3. Getter和Setter
计算属性默认是只读的,也就是只用到getter
。当你尝试修改一个计算属性时,你会收到一个运行时警告。只在某些特殊场景中你可能才需要用到“可写”的属性,你可以通过同时提供 getter
和 setter
来创建:
<!-- vue2 -->
<script>
export default {data() {return {firstName: "Jack",lastName: "Ma"}},computed: {fullName: {// getterget() {return this.firstName + this.lastName;},// setterset(newValue) {// 注意:我们这里使用的是解构赋值语法[this.firstName, this.lastName] = newValue.split(' ')}}}, methods:{setNewName(){//设置值触发setterthis.fullName = "Tom Mao"console.log(this.firstName, this.lastName);}}
}
</script>
<!-- vue3 -->
<script setup>
import { ref, computed } from "vue"const firstName = ref("J.K.")
const lastName = ref("Rowling")const fullName = computed({get() {return firstName.value + lastName.value},set(newValue) {[firstName.value, lastName.value] = newValue.split(' ')}
})const setNewName = function() {fullName.value = "John Doe"
}
</script>
4. Getter 不应有副作用
需要注意的是,computed
属性必须返回一个值,不能有副作用,如修改数据或触发异步操作等。如果需要有副作用的计算,可以使用watch
属性。