0

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?

2
  • You need to access the object to get the ref Commented Nov 10, 2017 at 8:09
  • Thats what i have done, v-model="pays[key].ref" Commented Nov 10, 2017 at 8:28

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.