说明
- 父组件校验子组件表单规则,想在子组件写一个方法返回校验结果(true,false),然后在父组件中调用。然而...道路曲折。虽然最终解决方法很简单,是某个校验方法中漏写了callback(),但在解决过程中也学到了一些其他的知识。
过程
- 比较自己写的和以前项目中的方法,感觉没啥毛病,但试了以后就是不行,期间尝试debug,log,但校验方法始终返回undefined。但实际这两个方法都可以。
自己写的方法
customValidate() {
this.$refs.xxx.validate(valid => {
this.flag = valid;
})
return this.flag;
},
以前项目中方法
validate() {
let res
this.$refs['xxx'].validate((valid) => {
if (valid) {
res = true
} else {
res = false
}
})
return res
}
- 网上搜索过程中,看到了同时校验多个表单的方法,也算是收获了。
const form1 = new Promise((resolve, reject) => {
this.$refs['father'].$refs['child1'].validate(valid => {
if (valid) {
resovle();
} else {
reject();
}
})
});
const form2 = new Promise((resolve, reject) => {
this.$refs['father'].$refs['child2'].validate(valid => {
if (valid) {
resovle();
} else {
reject();
}
})
});
Promise.all([form1, form2])
.then(ress => {
this.todoSth();
})