定义
计算属性(computed)是 Vue.js 中的一个特性,它可以根据依赖的响应式数据自动计算出一个新的值,并且在依赖数据发生改变时重新计算。它有两个特点:
- 缓存:计算属性的结果会被缓存,只有当依赖的响应式属性发生变化时才会重新计算。多次访问同一个计算属性时,直接返回缓存的结果,提高性能。
- 惰性求值:计算属性是惰性求值的,只有在计算属性被读取时才会进行计算。如果计算属性的依赖项发生变化但没有被读取,计算不会触发,避免不必要的计算和性能浪费。
语法
在 Vue 实例中定义计算属性时,需要在computed选项中添加对应的计算属性键值对,其中键是计算属性的名称,值可以是一个函数或对象。
<template>
<div>
<input v-model="range" placeholder="请输入起始点和终点(起点-终点)" />
<p>起点:{{ start }}, 终点:{{ end }}</p>
<p>坐标:{{ point }}</p>
<p>差值:{{ diff }}</p>
</div>
</template>
<script>
export default {
data: {
start: "", // 起点
end: "", // 终点
},
computed: {
// case 1. 函数写法
point: function () {
return {
start: this.start,
end: this.end,
};
},
diff: () => this.end - this.start,
// case 2. 对象写法
range: {
get: function () {
return this.start + "-" + this.end;
},
set: function (newValue) {
var arr = newValue.split("-");
this.start = arr[0];
this.end = arr[arr.length - 1];
},
},
},
};
</script>