gpt4 book ai didi

Vue.js 如何计算总数?

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:23 25 4
gpt4 key购买 nike

如何计算数组的总量?

我将数据作为 prop 传递给子组件,但我被困在这里。当我控制 log 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>

最佳答案

如果其他人和我处于同样的情况,我想我会添加这个答案。我需要从嵌套对象中获取值,然后在减少它们之前将它们推送到一个数组中:

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 循环遍历如下所示的对象:

orders = {
1: {title: 'Google Pixel', price: 3000},
2: {title: 'Samsung Galaxy S8', price: 2500},
3: {title: 'iPhone 7', price: 5000}
}

然后您可以在模板中显示总数:

<span> {{total}} </span>

关于Vue.js 如何计算总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com