16

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>

1 Answer 1

18

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
     }
   ...
Sign up to request clarification or add additional context in comments.

5 Comments

sometimes, updating some array item on your data does not update the DOM directly and you must enforce Vue to do that. Like stackoverflow.com/questions/39794632/…
thanks, looks like Vue doesnt detect changes on object array if you add a property like data[index].prop = value I did $this.set(item, 'prop', value) and it worked vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
Late comment but it might still be useful to someone that stumbles upon it: remember to set your component keys! <input type="text" v-model="items[index].prop2" :key='items[index].unique_prop'> NOT <input type="text" v-model="items[index].prop2" :key='item.unique_prop'> I experienced that the latter does not work with item slots on v-autocomplete components. Probably others too.
Shoudn't @input="updateMyProp(index) be @input="updateMyProp($event, index)?
Is this issue fixed in vue3?

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.