Reputation: 379
I would like to bind v-model to an array of values
So i have
paymenttypes:[
{label:'cheque', value:1},
{label:'two', value:2}
]
pays:[],
created(){
this.paymentmethods.forEach((value) => {
this.pays.push({id:value.value, ref: '' , val: 0 })
});
}
now on the template
<div class="row saleTotal" v-for="(key, extrafieldsDetails) in paymentmethods">
<div class="col-sm-4">
<h5>{{extrafieldsDetails.label}}</h5>
</div>
<div class="col-sm-4">
<input type="number" min="0" class="text-right form-control" v-model="pays[key].ref">
</div>
</div>
But am getting an error
cannot read property 'ref' of undefined
What could be wrong? as the pays array has a object with a key of ref. Where am i going wrong?
Upvotes: 0
Views: 5011
Reputation: 14531
I am assuming that your variables paymenttypes
and paymentmethods
are the same.
If so, your v-for
binding is incorrect. You do not get key-value pairs out of paymentmethods
because it is an array, not an object.
So, your v-for
could be written as v-for="(item, index) in paymentmethods"
where item
is the array item from paymentmethods
, and index
is the index of item
in paymentmethods
.
Then you would need to replace the property accessors as follows:
{{item.label}}
instead of {{extrafieldsDetails.label}}
pays[index].ref
instead of pays[key].ref
var app = new Vue({
el: "#app",
data: {
paymentmethods:[
{label:'cheque', value:1},
{label:'two', value:2}
],
pays:[]
},
created(){
this.paymentmethods.forEach((value) => {
this.pays.push({id:value.value, ref: '' , val: 0 })
});
console.log(this.pays);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div class="row saleTotal" v-for="(item, index) in paymentmethods">
<div class="col-sm-4">
<h5>{{item.label}}</h5>
</div>
<div class="col-sm-4">
<input type="number" min="0" class="text-right form-control" v-model="pays[index].ref">
</div>
</div>
</div>
Upvotes: 1