如何对对象数组进行 v-model

Jam*_*cay 6 vue.js

我有对象数组,这是不定数组,可以在这里推送或拼接东西。我需要使用 vue 将对象的属性绑定到输入 dom,似乎不起作用。

这是数据

   items : [
     { prop1: 123, prop2: 'test', prop3: 'foo' },
     { prop1: 321, prop2: 'tset', prop3: 'bar' },
   ]

}
Run Code Online (Sandbox Code Playgroud)

试图做


   <li v-for="item in items"> 
      {{ item.prop2 }} 
      <input type="text" v-model="item.prop1">
   </li>

</ul>
Run Code Online (Sandbox Code Playgroud)

小智 6

你可以使用索引来做到这一点。例如:

   <li v-for="(item, index) of items"> 
      {{ item.prop2 }} 
      <input type="text" v-model="items[index].prop2">
   </li>
Run Code Online (Sandbox Code Playgroud)

另一种方法,我推荐它是使用一个事件,就像v-on:input或只是@input在你输入一个调用一个方法,在你的项目中找到你的项目items来改变你的prop2价值。

   <li v-for="(item, index) of items"> 
      {{ item.prop2 }} 
      <input type="text" @input="updateMyProp(index)">
   </li>
Run Code Online (Sandbox Code Playgroud)
   ...
   methods: {
     updateMyProp ($event, index) {
       // your update logic here
       // you can use 'this.items', Object.assign, Vue.set, etc... to update your value
     }
   ...
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,如果您添加像“data[index].prop = value”这样的属性,看起来 Vue 不会检测到对象数组的更改,我做了“$this.set(item, 'prop', value)”并且它有效 https:// /vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats (2认同)