【问题标题】:Vue.js How to calculate totals?Vue.js 如何计算总数?
【发布时间】:2016-12-31 05:03:33
【问题描述】:

如何计算数组的总量?

我将数据作为道具传递给子组件,我被困在这里。当我控制台 log 道具时,它返回一个非常复杂的 object 。我尝试了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>

【问题讨论】:

  • 在这里工作,请分享更多代码

标签: vue.js


【解决方案1】:

按照您的建议,您可以使用Array#reduce 函数。 Starting from this example on SO,您可以根据自己的需要调整它,只需将value.total 添加到总和中。

要计算所有值的总和,您可以使用computed properties,它将在您的模板中显示为{{ total }}

<script>

export default {



    props: {
        values: {
            type: Array,
            default: []
        },
    }
    ready: function() {

    },
    computed: {
        total: function() {
            if (!this.values) {
                return 0;
            }

            return this.values.reduce(function (total, value) {
                return total + Number(value.total);
            }, 0);
        }
    }

}
</script>

注意:这当然只适用于value.total 是无单位数(例如1,而不是'1 USD')。否则,您还需要剥离 reduce 函数中的 。

【讨论】:

  • 感谢您的回答,但此函数返回:0100200 它应该返回 300,除了它给出警告,评估表达式时出错“function total() { return this.values.reduce(function (total, value) { return total + value.total; }, 0); }": TypeError: this.values.reduce is not a function
  • 请阅读:This will of course only work, if value.total is a unitless number。您的值需要是数字,否则您需要将它们转换为数字。我添加了一个示例。
  • 有可能,this.values 不是一个数组吗?还是没有定义?您可能应该添加一个默认值。我还添加了一个示例(包括道具验证)。
  • 感谢它的作品。当我检查道具验证时,它发出警告:无效的道具:道具“值”的类型检查失败。预期的数组,得到字符串。我将 prop 验证更改为 String,然后它给了我相同的警告,Expected String got Array error .. 为什么会这样?
  • 不确定。在将 values 传递到组件之前,它的实际值是多少?
【解决方案2】:
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
                }
            }
        });`

【讨论】:

    【解决方案3】:

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

    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>
    

    【讨论】:

    • 有什么理由将所有值推送到数组中,而不是像这样将它们相加:Object.entries(this.orders).forEach(([key, val]) =&gt; { total+=(val.price) });
    • 嗯,好问题,我想我可能正在使用数组来填充购物车数据,所以我已经逐项计费
    猜你喜欢
    • 2017-08-29
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2017-11-26
    • 2020-01-17
    相关资源
    最近更新 更多