粘贴可用的element-ui validateField局部校验
作者:qb
这篇文章主要为大家介绍了粘贴可用element-ui中validateField局部校验示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
正文
element-ui
的表单提交基本每个项目都会使用到,其中针对特定区域的值进行校验的场景也不少,其文档相对简单,下面就贴上代码,复制粘贴到一个.vue
文件即可运行。
场景:人员信息录入时,表单可以就其中某一行进行保存,也可创建多个后批量保存,保存时如果信息不全会只针对当前行进行校验。
1、template
<template> <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="80px"> <div v-for="(domain, index) in dynamicValidateForm.domains" :key="index" class="form-item" > <el-form-item> {{ index + 1 }} </el-form-item> <el-form-item label="姓名" size="mini" :prop="'domains.' + index + '.name'" :rules="{ required: true, message: '姓名不能为空', trigger: 'blur', }" > <el-input v-model="domain.name"></el-input> </el-form-item> <el-form-item label="年龄" size="mini" :prop="'domains.' + index + '.age'" :rules="{ required: true, message: '年龄不能为空', trigger: 'blur', }" > <el-input v-model="domain.age"></el-input> </el-form-item> <el-form-item label="地址" size="mini" :prop="'domains.' + index + '.address'" :rules="{ required: true, message: '地址不能为空', trigger: 'blur', }" > <el-input v-model="domain.address"></el-input> </el-form-item> <el-form-item label="手机" size="mini" :prop="'domains.' + index + '.phone'" :rules="{ required: true, message: '手机不能为空', trigger: 'blur', }" > <el-input v-model="domain.phone"></el-input> </el-form-item> <el-form-item> <el-button size="mini" type="primary" @click="saveCurrentData(domain, index)" >保存</el-button > </el-form-item> </div> <el-form-item class="form-footer"> <el-button type="primary" size="mini" @click="submitForm('dynamicValidateForm')" >全部保存</el-button > <el-button size="mini" @click="resetForm('dynamicValidateForm')">重置</el-button> </el-form-item> </el-form> </template>
2、script
<script> export default { data() { return { dynamicValidateForm: { domains: [], }, }; }, created() { const item = { name: "", age: "", address: "", phone: "", }; for (let i = 0; i < 5; i++) { this.dynamicValidateForm.domains.push(Object.assign({}, item)); } }, methods: { // 定义局部校验函数 validateFn(domain, index) { let validateFieldArr = ["name", "age", "address", "phone"]; return new Promise((resolve, reject) => { for (let item of validateFieldArr) { this.$refs.dynamicValidateForm.validateField( `domains.${index}.${item}`, (err) => { if (err) { return reject(err); // 失败返回err } resolve(true); // 成功返回true } ); } }); }, async saveCurrentData(domain, index) { const validateResult = await this.validateFn(domain, index); if (validateResult) { console.log("-------校验通过啦------"); } }, submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { alert("submit!"); } else { return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); }, }, }; </script>
3、style
<style> .form-item { display: flex; } .form-footer { display: flex; justify-content: center; } </style>
以上就是粘贴可用element-ui中validateField局部校验的详细内容,更多关于element-ui validateField局部校验的资料请关注脚本之家其它相关文章!