1

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

输出

{  "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" }, 
 }

小提琴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);
       }
    },
})
4

1 回答 1

1

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

   prop: function(obj, prop, event) {
     const data = this.travellerDetails[obj] || {}
     data[prop] = event.target.value
     this.travellerDetails = {
        ...this.travellerDetails,
        [obj]: {...data}
     }
   }
于 2019-07-23T02:26:44.563 回答