使用vuejs和laravel获取表中元素的总和

问题描述 投票:0回答:1

我正在使用vuejs和laravel,我希望在包含数量,单价和总计的表格中获得总金额。现在我想在循环数据库元素并使用v-if获取某些元素之后得到它们的总数。我该怎么做...提前谢谢。 this is the view

这是我的代码

 <table id="example1" class="table table-bordered table-striped table-hover">
          <thead>
            <th>Decription</th>
            <th>Quantity</th>
            <th>Unit price</th>
            <th>Total</th>
            <th>Create on</th>
          </thead>
          <tbody>
            <tr v-for="item, key in pass" v-if="list.quotation_no === item.quotation_id">
              <td>{{ item.description }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ item.unit_price }}</td>                  
              <td>{{ item.quantity * item.unit_price }}</td>
              <td>{{ item.created_at }}</td><br>
            </tr>     
          </tbody>
        </table>
laravel vue.js
1个回答
0
投票

您可以定义一个方法:

rowTotal(base) {
   return this.pass.reduce( (sum,cur) => sum+cur[base] , 0);
}

并像这样使用它:

<tfoot>
  <tr>
     <th>Total</th>
     <th>{{ rowTotal('quantity') }}</th>
     <th>{{ rowTotal('unit_price') }}</th>
     <th>{{ sumTotal }}</th>
   </tr>     
</tfoot>

但这将是你的pass的总和,因为这不是检查条件list.quotation_no === item.quotation_id。为此,您需要使用过滤数据的计算方法:

filteredPass() {
 return this.pass.filter( x => list.quotation === x.quotation_id);
}

您还需要定义一个计算值,用于乘以总和的总和,因为我们无法在数据绑定中计算内联:

computed: {
  sumTotal() {
    const summation = this.filteredPass();
    return summation.reduce((sum, cur) => sum += cur.unit_price * cur.quantity, 0)
  }
}

现在,您可以在html中修改v-for。只需更换以下内容:

<tr v-for="item, key in pass" v-if="list.quotation_no === item.quotation_id">

有了这个:

<tr v-for="(item, key) in filteredPass" :key="key">
<!-- better to use :key -->

以下是您可能有兴趣观看的一些链接列表:

Array.prototype.reduce

computed properties and watchers

Why key binding is better?

© www.soinside.com 2019 - 2024. All rights reserved.