1👍
✅
First you’re binding incorrectly the inputs to your array items, the correct is v-model="line.number"
v-model="lines[index].number"
:
<div class="row" v-for="(line, index) in form" :key="index">
<input
type="number"
placeholder="Number"
class="form-control"
:ref="`number_${index}`"
v-model="form[index].number"
@keyup.enter="goNext(index)"
/>
<input
type="number"
v-model="form[index].amount"
class="form-control"
placeholder="Amount"
:ref="`amount_${index}`"
@keyup.enter="addLine(index)"
/>
</div>
The total should be a computed property by using reduce
method like :
computed:{
total(){
return this.form.reduce((acc,curr)=>{
return acc+Number(curr.amount);
},0);
}
}
new Vue({
el: '#app',
data() {
return {
form: [{
number: 0,
amount: 0
}]
};
},
methods: {
addLine(index) {
this.form.push({
number: 0,
amount: 0
})
},
goNext(index) {
}
},
computed: {
total() {
return this.form.reduce((acc, curr) => {
return acc + Number(curr.amount);
}, 0);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>Total : {{total}}</div>
<div class="row" v-for="(line, index) in form" :key="index">
<input type="number" placeholder="Number" class="form-control" :ref="`number_${index}`" v-model="form[index].number" @keyup.enter="goNext(index)" />
<input type="number" v-model="form[index].amount" class="form-control" placeholder="Amount" :ref="`amount_${index}`" @keyup.enter="addLine(index)" />
</div>
</div>
Source:stackexchange.com