常见写法
methods: {
submit() {
let isValid = true
this.formRefs.forEach(ref => {
this.$refs[ref].validate(valid => {
if (!valid) {
isValid = false
}
})
}}
if (isValid) {
}
}
问题1:如果一个vue页面中出现两个以上的from表单应该如何简洁的进行校验
解决问题1:
- 通过给每个
<form>组件添加ref属性,然后通过this.$refs.xxx找到表单组件
- 把所有表单组件的实例放到一个数组当中,然后通过
Promise.all方法对表单进行批量校验
mounted() {
this.forms = [this.$refs.form1Ref, this.$refs.form2Ref]
},
methods: {
onSubmit(){
Promise.all(this.forms.map(t=>t.validate())).then(res=>{
console.log(res);
console.log('成功');
}).catch(err=>{
console.log(err);
console.log('失败');
})
}
问题2:如果一个页面中有较多子组件,并且子组件里面含有from表单,如何优雅校验
解决问题2:
- 通过组件的
$children属性获取当前组件所有子组件,然后判断它的options.name是否为Form判断它是否是表单组件
- 通过递归的方式按照上述方式,得到所有的表单组件实例
- 把所有表单组件的实例放到一个数组当中,然后通过
Promise.all方法对表单进行批量校验
data(){
return {
forms: []
}
},
mounted() {
this.findFormComponent(this.$children)
},
methods: {
findFormComponent(children) {
children.forEach((item) => {
if (item.$options.name === 'Form') {
this.forms.push(item)
} else {
item.$children && this.findFormComponent(item.$children)
}
})
},
onSubmit(){
Promise.all(this.forms.map(t=>t.validate())).then(res=>{
console.log(res);
console.log('成功');
}).catch(err=>{
console.log(err);
console.log('失败');
})
}
}