James Masangcay
James Masangcay

Reputation: 163

how to v-model for array of objects

I have and array of objects, this is indefinite array, may push or splice things here. I need to bind the property of an object to a input dom with vue, doesnt seem to work.

heres the data

   items : [
     { prop1: 123, prop2: 'test', prop3: 'foo' },
     { prop1: 321, prop2: 'tset', prop3: 'bar' },
   ]

}

trying to do


   <li v-for="item in items"> 
      {{ item.prop2 }} 
      <input type="text" v-model="item.prop1">
   </li>

</ul>

Upvotes: 16

Views: 22622

Answers (1)

Vitor Bertulucci
Vitor Bertulucci

Reputation: 196

You could use index to do that. For example:

   <li v-for="(item, index) of items"> 
      {{ item.prop2 }} 
      <input type="text" v-model="items[index].prop2">
   </li>

Another way to do that and I recommend it is to use a event, like v-on:input or simply @input on yout input an call a method that find your item in your items to change your prop2 value.

   <li v-for="(item, index) of items"> 
      {{ item.prop2 }} 
      <input type="text" @input="updateMyProp(index)">
   </li>
   ...
   methods: {
     updateMyProp ($event, index) {
       // your update logic here
       // you can use 'this.items', Object.assign, Vue.set, etc... to update your value
     }
   ...

Upvotes: 18

Related Questions