用Promise.all做多个表单校验
有时候,我们需要对多个表单进行同时校验,只有都校验通过才可以进行下一步。比较简单的方法就是,if(){}else{}嵌套使用,if A表单校验成功,再校验B表单。其实js提供了promise方法来帮助我们实现这一功能,代码如下:
const p1 = new Promise((resolve, reject) => {
this.$refs.projectInfo.validate(valid => {
if (valid) {
resolve(); //完成态
} else {
reject(); //已失败
}
});
});
const p2 = new Promise((resolve, reject) => {
this.$refs.projectInfo2.validate(valid => {
if (valid) {
resolve();
} else {
reject();
}
});
});
Promise.all([p1, p2]).then(() => {
// 表单验证通过,写业务代码
saveChild(this.projectInfo).then(res => {
if (res.data.success) {
this.$message.success('添加成功!');
this.childDialog = false;
this.initDate();
}
});
}).catch((error) =>{
this.$message.error("表单校验不通过!")
})