表单效验功能
1创建表单
<el-dialog v-model="dialogFormVisible" @close="clos" > <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon> <el-form-item label="名称" :label-width="formLabelWidth" prop="name">//prop字段名称 <el-input v-model="form.name" autocomplete="off" placeholder="请输入名称" /> </el-form-item> <el-form-item label="名称" :label-width="formLabelWidth" prop="title"> <el-input v-model="form.title" autocomplete="off" placeholder="请输入名称" /> </el-form-item> </el-form> </el-dialog>
2获取弹窗数据
const form = reactive({ name: '', title:'', });
3进行效验
const rules = reactive({ name: [{ required: true, message: '请输入完整内容', trigger: 'blur' }], title: [{ required: true, message: '请输入完整内容', trigger: 'blur' }] });
4自定义校验
const imgA = (rule, value, callback) => { if (!value) { return callback(new Error('请上传图片')); } callback(); }; const rules = reactive({ img: [{ required: true,validator: imgA , trigger: 'change' }], });
5提交判断所有校验
const dialogFormVisibles = () => { //获取所有需要校验的值 if (!ruleFormRef.value) return; ruleFormRef.value.validate((valid, fields) => { //判断是否有值 if (valid) { console.log('submit!'); dialogFormVisible.value = false; ElMessage({ message: '提交成功', type: 'success', }); } else { console.log('error submit!', fields); ElMessage({ message: '请将内容输入完整', type: 'warning', }); console.log(ruleFormRef.value); } }); };
6关闭弹窗清空校验数据
const ruleFormRef = ref(); const clos = () => { ruleFormRef.value.resetFields(); };