计算属性computed
计算属性的基本使用
案例拼接firstName和lastName
可以用methods中的方法实现
<h2>{{getFullName()}}</h2>
......
methods:{
getFullName() {
return this.firstName + ' ' + this.lastName
}
}
现在用计算属性实现
<h2>{{fullName}}</h2>
......
computed:{
fullName(){
return this.firstName + ' ' + this.lastName
}
}
问题:二者代码区别不大,为什么要选择用计算属性?
选择计算属性的原因
计算属性具有缓存,在不改变变量只重复使用时,计算属性只会调用一次,而methods中的方法使用几次就调用几次
案例:计算总价格并多次调用
data: {
books: [
{id:110,name:'Unix编程', price:119},
{id:111,name:'代码大全', price:105},
{id:112,name:'深入理解计算机原理', price:98},
{id:113,name:'现代操作系统', price:87},
]
},
- 用methods中的方法:
<h2>总价格:{{getTotalPrice}}</h2>
<h2>总价格:{{getTotalPrice}}</h2>
<h2>总价格:{{getTotalPrice}}</h2>
<h2>总价格:{{getTotalPrice}}</h2>
......
methods: {
getTotalPrice:function (){
let result = 0
for (let i=0;i<this.books.length; i++){
result += this.books[i].price
}
return result
}
},
在控制台可以看到打印次数为4次
- 用计算属性实现
<h2>总价格:{{totalPrice}}</h2>
<h2>总价格:{{totalPrice}}</h2>
<h2>总价格:{{totalPrice}}</h2>
<h2>总价格:{{totalPrice}}</h2>
......
computed:{
totalPrice(){
let result = 0
for (let i=0;i<this.books.length; i++){
result += this.books[i].price
}
return result
}
在控制台可看出调用了4次,只打印了一次
computed的set/get方法
使用计算属性时,不加()的原因,就像Java实体类中的属性一样,具有get/set方法,
一般不设置set方法,为只读属性
computed:{
//完整的计算属性
fullName: {
//一般不设置set方法,只读属性
set:function (newValue){
console.log('--------',newValue);
},
get:function (){
return this.firstName+ ' ' + this.lastName;
}
}
}
简化后:
computed:{
//简化后的计算属性
fullName() {
return this.firstName+ ' ' + this.lastName;
}
}