Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: two-way data binding using object with v-for

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>
like image 522
david Avatar asked Oct 27 '25 08:10

david


1 Answers

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.

like image 120
Saurabh Avatar answered Oct 28 '25 20:10

Saurabh