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);
}
}
})