項(xiàng)目中經(jīng)常會(huì)用到動(dòng)態(tài)添加表單項(xiàng)的功能
QQ截圖20210923093405.jpg
一般遇到這個(gè)功能,我們必須要考慮到一些問(wèn)題:
- 驗(yàn)證前面是否有空項(xiàng)曼玩,有空則不能繼續(xù)添加鳞骤,并作出驗(yàn)證提示;
-
添加項(xiàng)可以刪除黍判,但必須至少保留一項(xiàng)
QQ截圖20210923093015.jpg
因?yàn)槭莿?dòng)態(tài)添加表單項(xiàng)豫尽,所以這個(gè)表單項(xiàng)肯定是個(gè)數(shù)組,每項(xiàng)包含兩個(gè)屬性顷帖,sectionId
和preFileId
formData: {
sections: [{sectionId: '', preFileId: ''}]
},
rules: {
required: [{ required: true, message: '此項(xiàng)不能為空'}]
},
主體代碼
<el-row v-for="(section, index) in formData.sections" :key="index">
<i @click="delSection(index)" class="el-icon-delete btn-delete" v-if="formData.sections.length > 1"></i>
<el-col :span="12">
<el-form-item :label="'公告關(guān)聯(lián)標(biāo)段' + (+index +1)" :prop="'sections.' + index + '.sectionId'" :rules="rules.required">
<el-select v-model="section.sectionId" placeholder="請(qǐng)選擇標(biāo)段" style="width: 100%;">
<el-option v-for="item in sectionsList" :key="item.id" :label="item.label" :value="item.id"></el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item :label="'資格預(yù)審文件' + (+index +1)" :prop="'sections.' + index + '.preFileId'" :rules="rules.required">
<el-select v-model="section.preFileId" placeholder="請(qǐng)選擇預(yù)審文件" style="width: 100%;">
<el-option v-for="item in preFileList" :key="item.id" :label="item.label" :value="item.id"></el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row v-if="formData.sections.length < 6">
<el-col :span="24" style="text-align: right;">
<el-form-item label="" >
<el-button @click="newSection()" type="primary" plain icon="el-icon-plus" style="display: block;width: 100%;">新增標(biāo)段</el-button>
</el-form-item>
</el-col>
</el-row>
新增動(dòng)作美旧,這里用elementUI的表單項(xiàng)驗(yàn)證方法 validateField()
渤滞,方法接收參數(shù)可以是數(shù)組,該方法會(huì)依次驗(yàn)證數(shù)組中每個(gè)表單項(xiàng)榴嗅,也就是對(duì)應(yīng)的prop值妄呕,這里要注意,循環(huán)項(xiàng)的prop格式為 :prop="'sections.' + index + '.preFileId'"
嗽测。
但是validateField()
方法每驗(yàn)證通過(guò)一次就會(huì)執(zhí)行一次回調(diào)绪励,我們這里需要的是全部通過(guò)驗(yàn)證才執(zhí)行回調(diào),所以更改如下:
/**
新增標(biāo)段
*/
newSection() {
const { sections } = this.formData
let flag, validateFieldArrs = [];
sections.forEach((sec, index)=> {
//部分驗(yàn)證validateField接收的參數(shù)格式:['list.0.id', 'list.1.id']
validateFieldArrs.push(`sections.${index}.sectionId`, `sections.${index}.preFileId`)
if (sec.sectionId && sec.preFileId) {
flag = true
} else {
flag = false
}
})
if (flag) {
//全部驗(yàn)證通過(guò)執(zhí)行新增
this.formData.sections.push({sectionId: '', preFileId: ''})
} else {
//驗(yàn)證指定表單
this.$refs['formData'].validateField(validateFieldArrs)
}
},
/**
刪除標(biāo)段
@params {Number} index 刪除數(shù)據(jù)索引
*/
delSection(index) {
this.formData.sections.splice(index, 1)
}
最終效果
QQ錄屏202109231056332021923116292.gif