element 校验多个表单方法
<el-form :model="tableForm1" ref="tableForm1" :rules="rules1" label-width="100px" > <el-form-item label="价格" prop="price"> <el-input v-model.number="tableForm1.price" autocomplete="off"></el-input> </el-form-item> </el-form> <el-form :model="tableForm2" ref="tableForm2" :rules="rules2" label-width="100px" > <el-form-item label="年龄" prop="age"> <el-input v-model.number="tableForm2.age" autocomplete="off"></el-input> </el-form-item> </el-form>
rules1: { price: [{ required: true, message: '价格不能为空', trigger: 'blur' }] }, rules2: { age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }] },
submitForm () { const formName = ['tableForm1', 'tableForm2'] const validates = (item) => { return new Promise((resolve, reject) => { if (!this.$refs[item]) { resolve() return false } this.$refs[item].validate((valid) => { if (valid) { resolve() } else { reject(new Error('验证不对')) } }) }) } Promise.all(formName.map(item => validates(item))).then(() => { console.log('成功') }).catch(() => { console.log('失败') }) }