computed的写法
在vue2x中,computed option语法有2种格式。一种是函数写法,一种是对戏那个写法
函数写法
computed: {
fullName () {
...
}
}
对象写法
computed: {
fullName: {
get: function () {
...
},
set: function () {
...
}
}
}
<b>小提示:</b>set方法只有在属性值发生边改时才会触发
computed的应用场景
总的来说,computed的诞生其实是为了解决频繁计算的问题。
比如说以前我们要计算单价和数量得到合计,会写一个method方法来计算,值发生改变的时候都会去执行这个方法,这样写固然没有问题,不过这样的写法不是最优雅的方案,因为它会频繁的执行,消耗性能,所以computed来了。
computed还有其他很多场景,但其实都是为了解决这样的问题,降低损耗,提升性能
computed的作用
- computed计算属性依赖于其他属性和数据来计算值,只有数据发生改变,它才会执行,且只执行一次
- computed解决了频繁计算的问题,提高了性能
小栗子
通过计算firstName和lastName得到fullName
<h1>我是:{{ fullName }}</h1>
<h1>我是:{{ fullNameSub }}</h1>
<br />
<button @click="onRename">通过set就可以修改属性的值</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: "张",
lastName: "无忌",
};
},
computed: {
// getter写法
fullName() {
return this.firstName + this.lastName;
},
// setter写法
fullNameSub: {
get: function () {
return this.firstName + this.lastName;
},
set: function (newValue) {
console.log("newValue", newValue);
console.log("值更新的时候会触发set");
},
},
},
methods: {
onRename() {
this.firstName = "赵";
},
},
};
</script>