vue+element form多表单校验

一般项目中会对 Element Form 表单进行二次封装,封装后的通用表单,有时候不能适用一些特殊的表单,可以用到多表单组合一起验证,待都校验通过后再执行后续动作。

解决

先对每一个表单进行校验,返回一个 Promise 对象,然后使用Promise.all()方法对所有返回的 Promise 对象判断,全部是 fullfilled 的时候执行后续逻辑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<template>
<div>
<el-form ref="form1" :model="form1" :rules="rules1">
<el-form-item label="标题1" prop="title1">
<el-input v-model="form1.title1" placeholder="请输入标题1" />
</el-form-item>
<el-form-item label="内容1" prop="content1">
<el-input v-model="form1.content1" placeholder="请输入内容1" />
</el-form-item>
</el-form>

<el-form ref="form2" :model="form2" :rules="rules2">
<el-form-item label="标题2" prop="title2">
<el-input v-model="form2.title2" placeholder="请输入标题2" />
</el-form-item>
<el-form-item label="内容2" prop="content2">
<el-input v-model="form2.content2" placeholder="请输入内容2" />
</el-form-item>
</el-form>

<el-button type="primary" @click="onOk">确定</el-button>
</div>
</template>

<script>
export default {
name: 'MoreForm'
data() {
return {
form1: {
title1: '',
content1: ''
},
form2: {
title2: '',
content2: ''
},
rules1: {
title1: [
{ required: true, message: '请输入标题1', trigger: 'blur'}
],
content1: [
{ required: true, message: '请输入内容1', trigger: 'blur'}
]
},
rules2: {
title2: [
{ required: true, message: '请输入标题2', trigger: 'blur'}
],
content2: [
{ required: true, message: '请输入内容2', trigger: 'blur'}
]
}
}
},
methods: {
onOk() {
let formValidate = [
this.$refs['form1'].validate(),
this.$refs['form2'].validate()
]
Promise.all(formValidate).then(() => {
// todo
// 校验通过后的处理
})
}
}
}
</script>

相关链接

[1] Element > 组件 > Form 表单