element-ui——el-form校验循环对象
参考:https://www.cnblogs.com/duanzhenzhen/p/13502278.html
我的情况:form表单中有循环的值,且其下级也是循环的值,想要对每个值进行校验
效果:
html部分代码:
<el-form ref="form" label-width="140px" :model="form" :rules="rules" @submit.native.prevent > <div> <div v-for="(parent, parentIndex) in form.parentList" :key="parentIndex + 1" > <p class="title"> <span>父级对象{{ parentIndex + 1 }}</span> <el-link v-if="form.parentList.length > 1" type="danger" @click="deleteParent(parentIndex)" >删除父级对象</el-link > </p> <el-row :gutter="100"> <el-col :span="12"> <el-form-item label="名称:" :rules="rules.name" :prop="`parentList.${parentIndex}.name`" // <=== 关键 > <el-input v-model="parent.name" clearable size="large" placeholder="请输入" ></el-input> </el-form-item ></el-col> </el-row> <el-row v-for="(child, childIndex) in parent.childList" :key="`children-${childIndex}`" :gutter="100" > <el-col :span="12" ><el-form-item :label="`子级对象${childIndex + 1}-名称:`" :rules="rules.name" :prop="`parentList.${parentIndex}.childList.${childIndex}.name`" // <=== 关键 > <el-input v-model="child.name" clearable size="large" placeholder="请输入" ></el-input> </el-form-item> </el-col> <el-link v-if="parent.childList.length > 1" type="danger" @click="delChild(parentIndex, childIndex)" >删除子级对象</el-link > </el-row> <el-form-item> <el-link type="primary" @click="addChild(parentIndex)" >添加子级对象</el-link > </el-form-item> </div> <el-divider></el-divider> <el-row :gutter="100"> <el-col :span="12"> <el-form-item> <el-button type="primary" @click="addParent"> 新增父级对象 </el-button> <el-button type="success" @click.prevent="submit"> 提交 </el-button></el-form-item ></el-col > <el-col :span="12"> <el-form-item> </el-form-item></el-col> </el-row> </div> </el-form>
js部分代码:
data() { return { form: { parentList: [ { name: '', childList: [{ name: '' }], }, ], }, rules: { name: [{ required: true, message: '请输入', trigger: 'blur' }], }, parentListIndex: '', // 父级对象序号 childListIndex: '', // 子级对象序号 }; }, methods: { // 新增父级对象 addParent() { this.form.parentList.push({ name: '', childList: [{ name: '' }], }); }, // 删除父级对象 deleteParent(index) { this.$confirm('此操作将删除该父级对象, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => { this.form.parentList.splice(index, 1); }); }, // 添加子级对象 addChild(index) { this.form.parentList[index].childList.push({ name: '', }); }, // 删除子级对象 delChild(parentIndex, index) { this.$confirm('此操作将删除该子级, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => { this.form.parentList[parentIndex].childList.splice(index, 1); }); }, // 提交 submit() { this.$refs.form.validate((valid) => { if (valid) { console.log('提交'); } }); }, },