Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to v-model for array of objects

Tags:

vue.js

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>
like image 403
James Masangcay Avatar asked Nov 06 '19 01:11

James Masangcay


1 Answers

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
     }
   ...
like image 123
Vitor Bertulucci Avatar answered Nov 15 '22 02:11

Vitor Bertulucci