Vue笔记3-计算属性
Vue03 计算属性
computed计算属性和methods的区别就在于:
- computed计算只需要执行一次自动缓存的结果,之后每次调用都从缓存中直接调取结果,并且计算属性的调用可以和普通类属性一样直接引用,不需要以函数形式调用
- methods中方法的每次调用都需要重新进行计算
const app = new Vue({
el:"#app",
data:{
books:[
{
id:"001",
price:20,
},
{
id:"002",
price:30,
},
{
id:"003",
price:50,
},
],
},
computed:{
totalPrice:function(){
let result=0;
for(const book of this.books){
result+=book.price;
}
return result;
}
}
})
<div id="app">
<h1>书本总价:{{totalPrice}}</h1>
</div>
计算属性的set和get方法
每一个计算属性都包含一个set和get可以提供重写。
但是一般计算属性都是作为只读属性的,也就是直接省略set方法。
这种情况可以直接使用其get方法取代计算属性对象的声明
computed:{
set:function(newValue){
this.firstName = newValue.split(" ")[0];
this.lastName = newValue.split(" ")[1];
},
get:function(){
return `${this.firstName} ${this.lastName}`;
}
}
计算属性的缓存机制
computed会对参与计算的变量进行检测,如果没有发现参与计算的变量发生变化,则直接调用缓存的结果
computed:{
fullName:function(){
console.log("computed");
return `${this.firstName} ${this.lastName}`;
}
},
methods:{
getFullName:function(){
console.log("methods");
return `${this.firstName} ${this.lastName}`;
}
}
<h4>通过methods调用</h4>
<ul>
<li v-for="i in 4">{{getFullName()}}</li>
</ul>
<h4>通过computed调用</h4>
<ul>
<li v-for="i in 4">{{fullName}}</li>
</ul>


浙公网安备 33010602011771号