效果图:点击加号后会新增表单信息,点击删除,删除当前行。
代码如下:
<template>
<div class="border">
<div class="border-title">
<el-button type="success" size="small" circle @click="addList()">+</el-button>
</div>
<div class="border-contain">
<el-row style="padding: 5px;width: 99%" :key="index" v-for="(item,index) in dataForm.voList">
<el-col :span="6">
<el-form :ref="el => { if (el) dataFormVoListRef[index] = el }" :rules="dataVoListRules" :model="dataForm.voList[index]" label-width="70px" size="small" style="width: 100%;">
<el-form-item prop="qcName" label="质控表:" style="width: 100%">
<el-input v-model="dataForm.voList[index].qcName"></el-input>
</el-form-item>
</el-form>
</el-col>
<el-col :span="6">
<el-form :ref="el => { if (el) dataFormVoListRef[index] = el }" :rules="dataVoListRules" :model="dataForm.voList[index]" label-width="60px" size="small" style="width: 100%;">
<el-form-item prop="qcField" :label="labelName.qcFieldLabel[index]" style="width: 100%">
<el-input v-model="dataForm.voList[index].qcField"></el-input>
</el-form-item>
</el-form>
</el-col>
<el-col :span="1">
<el-button type="danger" size="small" @click="subList(index)" v-if="index>0" circle style="font-weight: bold">一</el-button>
</el-col>
</el-row>
</div>
<div style="padding: 1%">
<el-button @click="subFormData" type="success" size="small" >保存</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { reactive, ref,onBeforeUpdate } from "vue";
import { ElMessage } from 'element-plus/es'
let dataFormVoListRef = ref<any[]>([])
//表单信息
const dataForm = reactive<any>({
voList: [{
qcName: '',
qcField: '',
}],
})
//加号
const addList = () => {
dataForm.voList.push({
qcName: '',
qcField: '',
})
}
//减号
const subList = (index:any) => {
dataForm.voList.splice(index, 1)
}
let labelName = reactive<any>({
qcFieldLabel:['字段A','字段B','字段C','字段D','字段E','字段F','字段G','字段H','字段I','字段J','字段K','字段L',],
})
const dataVoListRules = ref({
qcName: [{ required: true, message: '', trigger: 'blur' }],
qcField: [{ required: true, message: '', trigger: 'blur' }],
})
// 确保在每次更新之前重置ref
onBeforeUpdate(() => {
dataFormVoListRef.value = [];
});
//提交表单基本信息/修改
const subFormData = () => {
let arry:any[] = []
for (let index = 0;index<dataForm.voList.length;index++) {
dataFormVoListRef.value[index].validate((valid: boolean | undefined) => {
arry.push(valid)
})
}
setTimeout(() => {
if (arry[arry.length-1] === true) {
console.log(1111);//调用接口
}else {
ElMessage.warning('表单信息未填写完整!')
}
},600)
}
</script>
<style lang="scss" scoped>
.border {
width: 96%;
margin-top: 3%;
margin-left: 1%;
border: 1px solid rgba(0, 0, 0, 0.31);
border-radius: 4px;
}
.border-title {
width: 50px;
background: white;
text-align: center;
margin-top: -12px;
margin-left: 10px;
}
.border-contain {
max-height: 40vh;
overflow: auto;
}
</style>