计算属性 — 求和及平均数
效果
![计算属性 — 求和及平均数](https://i-blog.csdnimg.cn/blog_migrate/e92c60631f96d264da67fca878418e1d.jpeg)
关键代码
HTML
<tr style="background-color: #eee">
<td>统计:</td>
<td colspan="2">总价钱为: {{ allPrice }}</td>
<td colspan="2">平均价: {{ avgPrice }}</td>
</tr>
data 参数
export default {
data() {
return {
name: "",
price: 0,
list: [
{ id: 100, name: "外套", price: 199, time: new Date('2010-08-12')},
{ id: 101, name: "裤子", price: 34, time: new Date('2013-09-01') },
{ id: 102, name: "鞋", price: 25.4, time: new Date('2018-11-22') },
{ id: 103, name: "头发", price: 19900, time: new Date('2020-12-12') }
],
};
},
computed 计算属性方法
computed: {
allPrice(){
return this.list.reduce((sum, obj) => sum += obj.price, 0);
},
avgPrice(){
return (this.allPrice / this.list.length).toFixed(2);
}
}