4

I'm having problems binding input data to object properties. I'm iterating through an object to generate input fields from its attributes, but the data binding won't work using v-model. Here's my code (the console log remains empty):

<div id="app">
<div v-for='value, key in fields'>
    {{ key }}: <input v-model='value'>
</div>
<button @click="add">Add</button>
</div>

<script>

new Vue({
el: '#app',
data: {
    fields: {
        id: 123,
        name: 'abc'
    }
},
methods: {
    add: function(){
          console.log('id: ' + this.fields.id)
          console.log('name: ' + this.fields.name)
    }
}
})

</script>

1 Answer 1

11

You will have to use fields[key] with v-model as value will not work there, it is an local variable of v-for.

<div id="app">
  <div v-for='(value, key) in fields'>
    {{ key }}: <input v-model="fields[key]">
  </div>
  <button @click="add">Add</button>
</div>

See working demo here.

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

1 Comment

Good grief this is subtle, but a very clear and concise explanation! Vue's documentation should have this in the Caveats section (this detail was surprisingly difficult to find through google and SO).

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.