computed是vue中常用的一个属性功能,它是属性调用,也带有缓存作用,computed监控自己定义的变量,变量直接在它内部定义就可以,只要变量值值有改变,则自定义重新调用计算属性执行一次。

computed属性的值是直接从缓存中获取,而不是重新编译执行一次,所以它的性能要高一些。

我们日常生活常见的购物车用computed计算属性编写再合适不过了,购物车中总金额的变化,会随着商品的数量和单价的变化而变化,下面是我看一本书写的一个购物车实例:

html页面代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="app">
<template v-if="list.length">
<table border="1" cellspacing="0" cellpadding="0" width="500" height="200">
<thead>
<tr>
<th> </th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
<th>操作</th>
</tr>
</thead>
<tbody v-for="(item,index) in list">
<tr>
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="countReduce(index)" :disabled="item.count===1">-</button>
<span>{{item.count}}</span>
<button @click="countAdd(index)">+</button>
</td>
<td><button @click="remove(index)">Remove</button></td>
</tr>
</tbody>

</table><br />

<div>总价:{{totalPrice}}/RMB</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/cart.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

cart.js代码:

new Vue({
el:"#app",
data:{
list:[
{
id:1,
name:'iphone7',
price:6888,
count:1
},
{
id:2,
name:'vivo x9s',
price:2400,
count:2
},
{
id:3,
name:'Huawei',
price:4500,
count:1
}

]
},
computed:{
totalPrice:function(){
var total=0;
for(var i=0;i<this.list.length;i++)
{
total+=this.list[i].price*this.list[i].count;
}
return total.toString().replace(/\B(?=(\d{3})+$)/g,',');
}
},
methods:{
countReduce:function(index){
if(this.list[index].count==1)
{
return;
}
this.list[index].count--;
},
countAdd:function(index){
this.list[index].count++;
},
remove:function(index){
this.list.splice(index,1);
}
}
})

 

效果图为:

从购物车实例来看,computed回调函数域中的回调函数方法可以在插值表达式{{}}中直接获取返回结果而无需在data数据域中定义相关的属性。这样用起来会方便很多。