在Vuejs中添加所有值

时间:2017-05-19 06:53:21

标签: vue.js

我不知道如何计算循环中的数量。

 <tr v-for="product in products">
        <td>{{ product.name }}</td>
        <td>
            <span v-for="price in product.prices" v-html=" '&#8369; ' + price.price + ', '"></span>
         </td>
       <td >
           <span v-for="quantity in product.quantities">{{ Need to total quantities here. }}</span>
       </td>
  </tr>

我的数据

enter image description here

我需要总计所有数量。我突出了数量。 TY

1 个答案:

答案 0 :(得分:2)

有一些变种。

<强>第一

您可以在获得产品数据时为其添加字段 脚本

this.products = someData;
this.products.forEach((pr) => {
   pr.totalQuantities = pr.quantities.map((q)=>q.qty).reduce(function(total, q) {
                 return total + q}, 0);
})

模板

<tr v-for="product in products">
        <td>{{ product.name }}</td>
        <td>
            <span v-for="price in product.prices" v-html=" '&#8369; ' + 
              price.price + ', '"></span>
         </td>
       <td >
           <span>{{product.totalQuantities}}</span>
       </td>
  </tr>

<强>第二

添加过滤器以计算总数 脚本(插入到vue实例中)

filters: {
    total: function (quantities) {
      return quantities.map((q)=>q.qty).reduce(function(total, q) {
                 return total + q}, 0);
    }
  }

模板

<tr v-for="product in products">
        <td>{{ product.name }}</td>
        <td>
            <span v-for="price in product.prices" v-html=" '&#8369; ' + 
              price.price + ', '"></span>
         </td>
       <td >
           <span>{{product.quantities | total}}</span>
       </td>
  </tr>

<强>第三

脚本

computed: {
   quantities(){
       return products.map(function(pr){
            return pr.quantities.map((q)=>q.qty).reduce(function(total, q) {
                 return total + q}, 0);
       });
   }
}

模板

<tr v-for="product, index in products">
        <td>{{ product.name }}</td>
        <td>
            <span v-for="price in product.prices" v-html=" '&#8369; ' + 
             price.price + ', '"></span>
         </td>
       <td >
           <span>{{ quantities[index] }}</span>
       </td>
  </tr>
使用索引

变体

脚本

   quantities(){
       return (index) => {
          return this.$store.getters.products[index].quantities.map((q)=>q.qt‌​y).reduce(function(t‌​otal, q) { return total + q}, 0) }
       }
   }

模板

{{quantities(index)}}