在一个计算器属性里可以完成各种复杂的逻辑,包括运算,函数调用等,只要最终返回一个结果就可以.
例: 下面示例展示的是在购物车内两个包裹的物品总价:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>示例</title>
</head>
<body>
<div id="app">
总价: {{ prices }}
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
package: [
{
name: 'iphone x',
price: 9000,
count: 2
},
{
name: 'ipad',
price: 4500,
count: 1
}
],
package2: [
{
name: 'apple',
price: 3,
count: 5
},
{
name: 'hanana',
price: 2,
count: 10
}
]
},
computed: {
prices: function () {
var prices = 0;
for (var i = 0; i < this.package.length; i++) {
prices += this.package[i].price * this.package[i].count;
}
for (var i = 0; i < this.package2.length; i++ ) {
prices += this.package2[i].price * this.package2[i].count;
}
return prices;
}
}
})
</script>
</body>
</html>
注: 当 package 或 package2 中的商品有任何变化, 比如购买数量变化或增删商品时,计算属性 prices 就会自动更新,视图中的总价也会自动变化.