如何获取<td>标签内的数量百分比?

时间:2019-08-21 01:58:55

标签: vue.js

我想获取每天数量的百分比。我正在使用方法来获取所有数量的总和。当我像这样distributed.Quantity将其组合到<td>{{distributed.Quantity / sumAllOfQuantity() * 100 | twoDecimal}}</td>时出现问题。我得到一个NaN值。如何计算每天的数量百分比。

HTML

<thead class="thead-info">
   <tr>
     <th>Avg. Qty / Day</th>
   </tr>
</thead>
<tbody v-if="distributed_per_day.length > 0">
   <tr v-for="(distributed, index) in distributed_per_day">
     <td>{{distributed.Quantity / sumAllOfQuantity() * 100 | twoDecimal}}</td>
   </tr>
</tbody>

方法

sumAllOfQuantity : function() {
    var sum = 0;
    for(var i = 0; i < this.distributed_per_day.length; i++) {
        sum += parseInt(this.distributed_per_day[i].Quantity);
    }
},

过滤器

twoDecimal(value) {
   return value.toFixed(2);
}

2 个答案:

答案 0 :(得分:1)

您的函数sumAllOfQuantity没有返回值,您可以在函数上添加return sum或在模板上的parseInt上添加distributed.Quantity或使用计算属性我建议的总数量,而不是多次调用的方法:

computed : {
  totalQuantity() {
    return this.distributed_per_day.reduce((acc,val)=> acc + parseInt(val.Quantity),0)
  }
}
<tr v-for="(distributed, index) in distributed_per_day">
   <td>{{ parseInt(distributed.Quantity) / totalQuantity * 100 | twoDecimal}}</td>
</tr>

答案 1 :(得分:1)

您应该像这样使用计算属性:

Vue.config.devtools = false
Vue.config.productionTip = false

new Vue({
  el: "#app",
  data: {
    distributed_per_day: [
      { Quantity: 1 },
      { Quantity: 2 },
      { Quantity: 3 }
    ]
  },
  computed: {
    sumAllOfQuantity() {
      return this.distributed_per_day.reduce((acc, item) => acc + item.Quantity, 0)
    }
  },
  filters: {
    twoDecimal(value) {
      return value.toFixed(2);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <thead class="thead-info">
     <tr>
       <th>Avg. Qty / Day</th>
     </tr>
    </thead>
    <tbody v-if="distributed_per_day.length > 0">
       <tr v-for="(distributed, index) in distributed_per_day">
         <td>{{(distributed.Quantity / sumAllOfQuantity * 100) | twoDecimal}}</td>
       </tr>
    </tbody>
  </table>
</div>