我正在寻找使用v-for动态添加div来输入细节的方法。所以我怎么能用v-for和v-model。现在,我面临一个问题,当我动态添加div时,第二个div会与第一个div v-model值一起克隆。下面我提到了代码。我有一个名为 Add 的按钮,该按钮调用 add()创建第二个循环。感谢所有帮助。
选择组件
let selectComponent = Vue.component('select-dropdown', {
props: ['defaultValue', 'items', 'selected'],
data() {
return {
selectedOption: this.selected,
dropdownOptions: this.items,
};
},
watch: {
selectedOption(val) {
this.$emit('update:selectedHazardList', val);
}
},
template: `<div>
<select class="form-control" v-model="selectedOption">
<option value=null> {{defaultValue}} </option>
<option v-for="item in dropdownOptions"
:value="item.id">{{item.Name}}</option>
</select>
</div>`,
});
文本框组件
let textboxComponent = Vue.component('text-box', {
props: {
placeHolder: {
type: String,
default: ''
},
value: {
type: String,
default: ''
}
},
template: `<div>
<input type="text" class="form-control" :value="value"
:placeholder="placeHolder"
@input="$emit('input', $event.target.value)"/>
</div>`,
});
TextArea组件
let textareaComponent = Vue.component('text-area', {
props: {
placeHolder: {
type: String,
default: ''
},
value: {
type: String,
default: ''
},
row: {
type: String,
default:'2'
}
},
template: `<div>
<textarea class="form-control" :value="value"
:placeholder="placeHolder" :rows="row"
@input="$emit('input', $event.target.value)"/>
</div>`,
});
主要组件:
let jobComponent = Vue.component('jha-potential-hazard', {
props: ['hazardItems'],
data() {
return {
selectedItems: [],
hazardDetails: '',
hazardConsequences:'',
DefaultValueForPotentialaHazardDropdown: "Select Potential Hazard",
selectedPotentialHazard: null,
currentIndex: 0,
jobStepModel: {
selectHazardId: new Array<string>(),
details: '',
potentialConsequence: '',
},
jobStepList:[]
};
},
methods: {
add() {
var Ph = {
"selectHazardId": this.selectedItems,
"details": this.hazardDetails,
"potentialConsequence": this.hazardConsequences
};
this.jobStepModel = Ph;
var jsonString = JSON.stringify(this.jobStepModel);
console.log(jsonString);
this.jobStepList.push(jsonString);
this.jobStepModel.selectHazardId.push("Select Potential Hazard");
},
SetIndexVariable(index: number) {
this.currentIndex = index;
},
}
template: `<div>
<div class="potential" style="background-color:#F8F8F8 !important;opacity:1" v-for="(jobStepModelobj, index) in jobStepModel.selectHazardId" v-on:click="SetIndexVariable(index)">
<div class="form-group row">
<div class="col-1">
<i class="fa fa-circle fa-3x" style="color:#9B9B9B;" aria- hidden="true"></i>
</div>
<div class="col-6">
<select-dropdown
:defaultValue="DefaultValueForPotentialaHazardDropdown"
:items="hazardItems" //Loads from api result
:selectedHazardList.sync="selectedItems"
:selected="selectedPotentialHazard">
</select-dropdown>
</div>
</div>
<div class="form-group row">
<div class="col-11">
<text-box v-model='hazardDetails'></text-box>
</div>
</div>
<div class="form-group row">
<div class="col-11">
<text-box v-model='hazardConsequences'></text-box>
</div>
</div>
</div>
</div>`,
});