[Vuejs]-Getting sum of elements in a table using vuejs and laravel

0👍

You can define a method:

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

And use it like so:

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

But this will total of your pass as this is not checking the condition list.quotation_no === item.quotation_id. For this, you need to use a computed method which filters the data:

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

You’ll also need to define a computed value for multiplying sum of the total as we can’t calculate inline in data-binding:

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

Now, you can modify the v-for in your html. Just replace the following:

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

With this:

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

Here are some list of links that you might be interested to watch:

Array.prototype.reduce

computed properties and watchers

Why key binding is better?

Leave a comment