计算属性 (computed)
1、案例
<div id = "app">
<h2>{{fullName}}</h2>
</div>
<script src = "../js/vue.js"></script>
<script>
const app = new vue({
el : "#app",
data : {
firstName : "Lebron",
lastName : "James",
},
computed : {
fullName : function (){
return this.firstName + " " +this.lastName
}
},
})
</script>
注:computed为计算属性,里面可以存放函数,函数中实现一些复杂操作。比较适合对多个变量或者对象进行处理后返回一个结果值。
2、计算属性的复杂操作
<div id = "app">
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src = "../js/vue.js"></script>
<script>
const app = new vue({
el : "#app",
data : {
books : [
{id : 110 , name : "unix" , price : 199},
{id : 111 , name : "代码" , price : 105},
{id : 112 ,name : "计算机" , price : 178},
{id : 113 , name : "系统" , price : 82},
]
},
computed : {
totalPrice : function (){
let result = 0;
for(let i = 0; i < this.books.length; i++){
result += this.books[i].price;
}
return result;
}
}
})
</script>
3、计算属性与methods的对比
计算属性占用的资源会更少。
当有一个性能开销比较大的的计算属性 A ,它需要遍历一个极大的数组和做大量的计算。然后我们可能有其他的计算属性依赖于 A ,这时候,我们就需要缓存。也就是使用 computed 而不是 methods。但对于每次都需要进行重新计算的属性比如下面这个函数的返回值 function () { return Date.now() } ,我们最好使用 methods。
总之:数据量大,需要缓存的时候用 computed ;每次确实需要重新加载,不需要缓存时用 methods 。