我已经有一个动态创建的现有表单。但是,我在向现有对象添加一组新的键值对时遇到了问题。我使用 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);
}
},
})