vue3 el-form表单校验规则在父组件触发

目前情况是 我form表单写在子组件,点击click在父组件,我想点击后在父组件触发校验

一. 取消el-form * 显示

 :hide-required-asterisk="true"

二. 子组件form表单设定校验规则后

 <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules"...


const rules = reactive({
  name: [
    { required: true, message: '请输入子票名称', trigger: 'blur' },
  ],
})



const ruleFormRef = ref();// ref
const validateFormMethod = () => {
  return new Promise((resolve, reject) => {
    if (ruleFormRef.value) {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          console.log('表单验证通过');
          resolve(valid);
        } else {
          console.log('表单验证不通过');
          reject(new Error('表单验证不通过'));
        }
      });
    } else {
      reject(new Error('表单引用未定义'));
    }
  });
};
defineExpose({
  ruleForm,
  validateFormMethod,

});

三.父组件

<ChildComponent ref="childComponentRef" />
const handlepresent = async () => {
  try {
    const isValid = await childComponentRef.value.validateFormMethod();
    if (isValid) {
      // 表单验证通过,执行一些操作
      console.log('执行操作');
      emit('present' , number.value);
    } else {
      // 表单验证不通过,执行其他操作
      console.log('表单验证不通过');
    }
  } catch (error) {
    console.error('验证过程中发生错误:', error);
  }
};
  <button @click="handlepresent">验证并执行操作</button>

大功告成!可在父组件内触发校验

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值