如何在通过 Vue Reactivity 创建的现有对象上添加键值对

How to add a key value pair on existing object created via Vue Reactivity

我已经有一个动态创建的现有表单。但是,我在向现有对象添加一组新的键值对方面遇到了问题。我使用 this.$set() 方法使用 Vue Reactivity,仅在 FIRST 对上成功。

输出

{  "traveller_1": { "gender": "c" }, 
   "traveller_2": { "gender": "f" }, 
   "traveller_3": { "gender": "i" } 
} 

预期输出

{ "traveller_1": { "firstname": "John", "age": "23", "gender": "m" }, 
  "traveller_2": { "firstname": "Jane", "age": "21", "gender": "f" }, 
  "traveller_3": { "firstname": "Jade", "age": "25", "gender": "f" }, 
 }

Fiddle https://jsfiddle.net/stda7Lwm/

查看

<div class="col-md-10" id="app"> {{ travellerDetails }}
   <div class="form-row" v-for="i in travellers"> 
      <div class="form-group col-md-6" v-for="(details, index) in bookingRequiredDetails">
         <label for="required-details">{{ details }}</label>
          <input 
             type="text" 
             class="form-control"
             @input="prop('traveller_' + i, details, $event)"
             placeholder="Required Details" 
           />
     </div>
   </div>
</div>

JS

new Vue({
  el: '#app',
  mounted  () {
  },
  data () {
        return {
                test: { 'unit1' : { life: 30}},
            travellerDetails: { },
            travellers: 3,
            bookingRequiredDetails: ['fullname', 'age', 'gender'],
        };
    },
 methods: {
             prop: function(obj, prop, event) {
        this.$set(this.travellerDetails, obj, { [prop] : event.target.value } );
        console.log(this.travellerDetails);
       }
    },
})

每次分配新值时,您都会覆盖所有对象。你应该只改变一个道具

   prop: function(obj, prop, event) {
     const data = this.travellerDetails[obj] || {}
     data[prop] = event.target.value
     this.travellerDetails = {
        ...this.travellerDetails,
        [obj]: {...data}
     }
   }