vue的计算属性:
当我们需要对我们的数据进行某种变化后再进行某种显示后,可以在计算属性中再重新定义一个属性,并且给他返回变化后的数据u
<h2>{{fullname}}</h2>
computed: {
fullname:function () {
return this.firstname + this.lastname
}
}
复杂操作:
<h2>总价格:{{totalPrice}}</h2>
data:{
books: [
{id:110,name:'UNIX编程艺术',price:119},
{id:111,name:'UNIX编程艺术',price:120},
{id:112,name:'UNIX编程艺术',price:121},
]
}
computed:{
totalPrice: function () {
let result = 0
for (let i=0; i<this.books.length;i++) {
result += this.books[i].price
}
return result
}
}
计算属性和方法methods之间的区别:
vue内部对computed做了一层缓存,它会观察你的这些东西有没有变化,比如this.firstname + this.lastname,如果每次调用的时候发现这些东西都没有变化的时候,直接会把原来的结果给返回去,这样做的话性能相对要高一些。
<h2>{{fullname}}</h2>
<h2>{{getFullName()}}</h2>
computed: {
fullname:function () {
return this.firstname + this.lastname
}
}
methods:{
getFullName: function () {
return this.firstname + this.lastname
}