子组件,只提取出来表单部分
<el-form
:inline="true"
:rules="rules"
label-width="150px"
:model="assetShowData"
ref="ruleFormRef"
>
</el-form>
在子组件中定义一个方法
methods: {
validate(callback){
//这个ruleFormRef是子组件内部el-form 的ref="ruleFormRef"
this.$refs.ruleFormRef.validate((valid) => {
callback(valid);
});
}
}
在父组件的弹框中引入子组件,并为子组件添加ref
<el-dialog
:model-value="isShow"
:title="title"
top="40px"
width="55%"
v-if="isShow"
@close="closeDialog"
>
<add-asset-dialog
v-model:isShow="addAssetVisible"
:showFormObj="showFormObj"
top="40px"
width="60%"
style="margin: 0 auto"
ref="formRef"
></add-asset-dialog>
<template #footer>
<span class="dialog-footer">
<el-button type="primary" @click="confirmClick">确定</el-button>
<el-button @click="closeDialog()">取消</el-button>
</span>
</template>
</el-dialog>
在confirmClick()提交表单时,调用子组件中的验证方法
//这个formRef是子组件标注的ref="formRef"
//这个validate 就是我们在自组件定义validate方法
confirmClick() {
(this.$refs.formRef as FormInstance).validate(async (valid) => {
if (valid) {//验证通过
const res = await addAsset(this.showFormObj);//请求后台接口
if (res.code === 0) {
ElMessage({
type: "success",
message: res.msg,
});
}
}
});
},
验证多个表单
const p1 = new Promise((resolve, reject) => {
this.$refs.form1.validate((valid) => {
if (valid) resolve();
});
});
const p2 = new Promise((resolve, reject) => {
this.$refs.form2.validate((valid) => {
if (valid) resolve();
});
});
Promise.all([p1, p2]).then(() => {
//全部验证通过就会走这里
});