如何计算阵列的总量?
我将数据传递给子组件作为prop,我被困在这里.当我控制日志道具时,它返回一个非常复杂的对象.我试过this.values.reduce()功能,但它不起作用.
<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>
Run Code Online (Sandbox Code Playgroud)
Pix*_*omo 14
如果其他人和我的情况相同,我想我会加上这个答案.我需要从嵌套对象中获取值,然后在减少它们之前将它们推送到数组:
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);
}
Run Code Online (Sandbox Code Playgroud)
这使用ES7 .entries循环遍历如下所示的对象:
orders = {
1: {title: 'Google Pixel', price: 3000},
2: {title: 'Samsung Galaxy S8', price: 2500},
3: {title: 'iPhone 7', price: 5000}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在模板中显示总计:
<span> {{total}} </span>
Run Code Online (Sandbox Code Playgroud)
小智 5
var payments = new Vue({
el: "#payments",
data: {
payments: [
{ name: "houseRent", amount: 1000, is_paid: true },
{ name: "houseRent", amount: 1500, is_paid: true },
{ name: "houseRent", amount: 1200, is_paid: false },
{ name: "houseRent", amount: 1070, is_paid: true },
{ name: "houseRent", amount: 1040, is_paid: false }
]
},
computed: {
totalAmount: function () {
var sum = 0;
this.payments.forEach(e => {
sum += e.amount;
});
return sum
}
}
});`
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16743 次 |
| 最近记录: |