gs-rp
gs-rp

Reputation: 377

How to sum values from a v-for in Vue.js from a computed value

I'm trying to sum the values computed inside a v-for using vuejs, however I believe it's not working because I can not access the value from the computed value inside the v-for.

I need to display the total value as the user in {{total}} which is the sum of v-model.number="totalItem(item)"

Could someone pls give me some directions? Thanks.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>

<div id="app">

    <button v-on:click="add">ADD ROW</button>

    <p>$: {{ total }}</p>

    <ul>
        <li v-for="(item, index) in items">
            <input type="text" v-model="item.name">
            <input type="number" v-model.number="item.quantity" min="1">
            <input type="number" v-model.number="item.price" min="0.00" max="1000000000.00" step="0.01">
            <input type="number" v-model.number="totalItem(item)" readonly>
            <button v-on:click="remove(index)">X</button>
        </li>
    </ul>



    <pre>{{ items | json}}</pre>


</div>


<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="vuejs.js"></script>
</body>

</html>

JavaScript - Vue.js

new Vue({
  el: '#app',
  data: {
    items: [{name: '', quantity: '', price: ''}]
  },
  methods: {
    add: function () {
      this.items.push({
        name: '',
        quantity: '',
        price: '',
        subTotal: ''
      })
    },
    remove: function (index) {
      this.items.splice(index, 1)
    },
    totalItem: function (item) {
      return item.price * item.quantity;
    }
  },
  computed : {
    total: function() {
      let sum = 0;
      return this.items.reduce((sum, item) => sum + item.price, 0);
    }
  }
})

Upvotes: 8

Views: 31765

Answers (4)

Dirceu Henrique
Dirceu Henrique

Reputation: 49

Short foreach, where you can put in getters.js for vuex

totalInvoice: (state) => {
    let sum = 0
    state.itens.forEach(  (item)  =>  sum += (item.value)  )
    return sum
} 

Upvotes: 0

Mengseng Oeng
Mengseng Oeng

Reputation: 813

  1. For
computed: {
  totalItem: function(){
      let sum = 0;
      for(let i = 0; i < this.items.length; i++){
        sum += (parseFloat(this.items[i].price) * parseFloat(this.items[i].quantity));
      }

     return sum;
   }
}
  1. ForEach
  computed: {
    totalItem: function(){
      let sum = 0;
      this.items.forEach(function(item) {
         sum += (parseFloat(item.price) * parseFloat(item.quantity));
      });

     return sum;
   }
}

Upvotes: 8

gs-rp
gs-rp

Reputation: 377

I've found my answer. It's simple.

v-model.number="item.total = item.quantity * item.price"

Upvotes: 8

frederickha
frederickha

Reputation: 368

Do something like this in the parent component:

computed: {
  total: function(){
  return this.items.reduce(function(prev, item){
  return sum + item.price; 
  },0);
 }
}

Upvotes: 5

Related Questions