Vue.js 如何计算总数? [英] Vue.js How to calculate totals?
问题描述
如何计算数组的总金额?
How can I calculate the total amount from an array?
我将数据作为 prop 传递给子组件,然后卡在这里.当我控制台 log prop 时,它返回一个非常复杂的 object .我尝试了 this.values.reduce()
函数,但它不起作用.
I pass data to the child component as prop, and I am stuck here. When I console log prop, it returns a very complicated object . I tried this.values.reduce()
function but it does not work.
<template>
<tr v-for="value in values" >
<th scope="row">{{$index+1}}</th>
<td>{{value.name}}</td>
<td>-</td>
<td>${{value.total}}</td>
</tr>
<tr>
<th></th>
<td><strong>Total:{{total}}</strong></td>
<td>-</td>
<td>-</td>
</tr>
</template>
<script>
export default {
props: ['values'],
ready: function() {
}
}
</script>
推荐答案
如果其他人和我有同样的情况,我想我会添加这个答案.我需要从嵌套对象中获取值,然后在减少它们之前将它们推送到数组:
In case anyone else is in the same situation as me I thought I'd add this answer. I needed to get the values from nested objects then push them to an array before reducing them:
total: function(){
let total = [];
Object.entries(this.orders).forEach(([key, val]) => {
total.push(val.price) // the value of the current key.
});
return total.reduce(function(total, num){ return total + num }, 0);
}
这使用 ES7 .entries
循环遍历如下所示的对象:
This uses ES7 .entries
to loop through the object which looked like this:
orders = {
1: {title: 'Google Pixel', price: 3000},
2: {title: 'Samsung Galaxy S8', price: 2500},
3: {title: 'iPhone 7', price: 5000}
}
然后您可以使用以下命令在模板中显示总数:
You can then display the total in your template with:
<span> {{total}} </span>
这篇关于Vue.js 如何计算总数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!