首页 > 解决方案 > 如何为具有多个字段的对象数组创建 v-model

问题描述

所以我为数组中的每个元素有 2 个复选框输入。第一个表示表单中的一个字段,第二个表示该字段是否需要,我需要像这样构造对象数组

    [
     {
      name: 'fieldName',
      required: true
     },
     {
      name: 'anotherFieldName'
     }
    ]

如果第一个复选框被选中,我需要在我的数组中添加一个具有“name”属性的对象,如果第二个复选框也被选中,我还需要添加“required”字段。

标签: vue.jsvuejs2

解决方案


尝试这个

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

或者

<li v-for="(item, index) of items"> 
      {{ item.prop2 }} 
      <input type="text" @input="updateMyProp(index)">
</li>

   ...
   methods: {
     updateMyProp ($event, index) {
       // your update logic here
       // you can use 'this.items', Object.assign, Vue.set, etc... to update your value
     }
   ...

推荐阅读