Vue 2 - Calculate total of rows input

Viewed 3197

I have a dynamic table with a quantity & price input, and I use a computed property to calculate each row's total. Now I need to find a way to calculate the grandtotal (sum of all subtotals).

HTML:

   <tr v-for="(item, index) in items">
      <td><input v-model.number="item.qty" size="10"></td>
      <td><input v-model.number="item.price" size="10"></td>
      <td><input v-model.number="subtotalRow[index]" readonly size="10"></td>
      <td><button @click="addRow(index)">+</button></td>
      <td><button @click="removeRow(index)">-</button></td>
   </tr>
   <tr>
      <td>Total: {{total}}</td>
   </tr>

Javascript:

computed: {
    subtotalRow() {
      return this.items.map((item) => {
        return Number(item.qty * item.price)
      });
    },
    // the index part is confusing me
    //
    // total() {
    //  return this.items.reduce((total, ?) => {
    //    return total + ?;
    //  }, 0);
    //}
},

I provided a small fiddle to make things clear.

https://jsfiddle.net/h5swdfv5/

I hope that some guidance can help me. Thank you in advance

1 Answers
Related