简体   繁体   English

Vue.js在V模型中绑定数组

[英]Vuejs bind an array in a v-model

I would like to bind v-model to an array of values 我想将v模型绑定到值数组

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. 因为pays数组有一个对象,其键为ref。 Where am i going wrong? 我要去哪里错了?

I am assuming that your variables paymenttypes and paymentmethods are the same. 我假设您的变量paymenttypespaymentmethods方式相同。

If so, your v-for binding is incorrect. 如果是这样,则您的v-for绑定不正确。 You do not get key-value pairs out of paymentmethods because it is an array, not an object. 您不会从paymentmethods获得键值对,因为它是一个数组, 而不是对象。

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 . 所以,你的v-for可以写成v-for="(item, index) in paymentmethods" ,其中item是从阵列项paymentmethods ,和index是指数itempaymentmethods

Then you would need to replace the property accessors as follows: 然后,您需要按以下方式替换属性访问器:

  • {{item.label}} instead of {{extrafieldsDetails.label}} {{item.label}}而不是{{extrafieldsDetails.label}}

  • pays[index].ref instead of pays[key].ref pays[index].ref代替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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM