多个form表单同时校验
1.新建mulitipleFormValid.js
/** * 多个表单同时校验 * @param {*} formRefs * @returns */ const validateForms = (formRefs) => { let objectList = []; let results = formRefs.map(formRef => new Promise((resolve, reject) => { formRef.validate((valid, object) => { if (valid) { resolve(); } else { objectList.push(object); reject(); } }); }) ) return Promise.all(results).catch(() => { return Promise.reject(objectList); }); } export default validateForms
2.在需要使用的页面引入js
import validateForms from '@/utils/mulitipleFormValid.js'
template代码只是一种举例方法<template>
<div> <el-form ref="workplacesForm1" :model="moduleObj" label-position="right" label-width="120px" label-suffix=":" :rules="tellRules" > <el-form-item label="" label-width="0" prop="functionName"> <el-input style="width: 200px" v-model="moduleObj.functionName" placeholder="请输入函数名" clearable :disabled="isdisabledModule" maxlength="300" show-word-limit /> </el-form-item> </el-form> <el-form ref="workplacesForm2" :model="moduleObj" label-position="right" label-width="120px" label-suffix=":" :rules="tellRules" > <el-form-item label="" label-width="0" prop="phone"> <el-input style="width: 200px" v-model="moduleObj.phone" placeholder="请输入电话" clearable :disabled="isdisabledModule" maxlength="11" show-word-limit /> </el-form-item> </el-form> </div> </template> <script> import validateForms from '@/utils/mulitipleFormValid.js' export default{ data(){ return { tellRules: { functionName: [ { message1: ['函数名不能为空', '函数名只能为英文、数字、特殊字符'], trigger: 'blur', validator: isNotChineseValid } ], phone: [ { message: '电话不能为空', trigger: 'blur', validator: isZeroValid } ] }, } } } </script>
let formRefs = ['workplacesForm1','workplacesForm2'].map(key => this.$refs[key]) validateForms(formRefs) .then(async () => { // 校验成功后处理内容区域 }) .catch(() => { return false })