instructions
- The parent component validates the child component form rules and wants to write a method in the child component that returns the validation result (true, false) and then call it in the parent component. However… The road twists and turns. Although the final solution was simple, missing callback() in one of the validation methods, there were a few other things you learned along the way.
process
- Comparing the method I wrote with the one in the previous project, I felt there was nothing wrong with it, but after trying it, I just couldn’t do it. During this period, I tried debug and log, but the verification method always returned undefined. But you can do either.
Write your own way
customValidate() {
this.$refs.xxx.validate(valid => {
this.flag = valid;
})
return this.flag;
},
Copy the code
Methods in previous projects
validate() {
let res
this.$refs['xxx'].validate((valid) => {
if (valid) {
res = true
} else {
res = false
}
})
return res
}
Copy the code
- In the process of searching online, I saw the method of verifying multiple forms at the same time, which is also a harvest.
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(); })Copy the code