VUE+ElementUI中,封装子组件中有多个form表单的校验,需同时校验,供父组件调用校验通过与否
【代码】VUE+ElementUI中,封装子组件中有多个form表单的校验,需同时校验,供父组件调用校验通过与否。
·
// 子组件封装方法
validateForm() {
return new Promise((resolve, reject) => {
// 收集所有表单引用
const forms = [
this.$refs.guaranteeForm,
this.$refs.mortgageForm,
this.$refs.pledgeForm,
];
// 过滤掉不存在的表单
const validForms = forms.filter((form) => form);
if (validForms.length === 0) {
resolve(true);
return;
}
// 存储所有表单的校验结果
const validResults = [];
// 遍历所有表单进行校验
validForms.forEach((form, index) => {
form.validate((valid) => {
validResults.push(valid);
console.log(validResults, "validResults");
// 当所有表单都校验完成后
if (validResults.length === validForms.length) {
// 检查是否所有表单都通过校验
const allValid = validResults.every((result) => result === true);
console.log(allValid, "allValid");
if (allValid) {
resolve(true);
} else {
resolve(false);
}
}
});
});
});
}
// 父组件调用
this.$refs['xxx']
.validateForm()
.then(() => {
// console.log("通过");
// 校验通过,执行后续操作
})
.catch((error) => {
// 校验失败逻辑
});
更多推荐


所有评论(0)