最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论