admin管理员组

文章数量:1318013

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>

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>
Share Improve this question asked Feb 15, 2017 at 10:48 daviddavid 431 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: javascriptVuejs twoway data binding using object with vforStack Overflow