vue3父组件对多个子组件校验、校验定位方法

需求:父组件点击保存按钮时,对多个子组件中的表单进行校验

解决方法:

父组件

<child
   ref="childRef"  // 第一步:给每个子组件标签添加ref
 >
</child>
<script setup>
const childRef= ref()  // 第二步:声明常量

 const save = ()=>{  // 保存事件
    const child= abilityRuleFormRef.value.ruleFormRef // 第六步:获取子组件暴露出的变量
    const childRES = new Promise((resolve, reject) => { // 创建Promise实例,为多个组件校验使用
        child.validate((valid, fields) => {
          if (valid) {
            resolve()
          } else {
            Object.keys(fields).forEach((v, index) => { // 第七步:通过scrollToField()方法完成校验定位
              if (index === 0) {
                const propName = fields[v][0].field
                child.scrollToField(propName)
              }
            })
            reject()
          }
        })
      })
    // 多个子组件校验
   Promise.all([formElRES, abilityRES, developRES, reprotMessageRES])
      .then(()=>{
        console.log('这里完成接口请求')
      })
      .catch(err => {
      ElMessage({
        message: '必填项不能为空',
        type: 'error'
      })
    })
     }
</script>

子组件

<template>
  <div class="child">
    <el-form ref="ruleFormRef"  // 第三步:给子组件表单添加ref
       :rules="rules.baseInfoRules"
       :model="data.personBesicInfo"
    >
    </el-form>
  </div >
</template>

<script setup>
const ruleFormRef = ref() // 第四步:声明常量
const rules = reactive({  // 校验规则
  baseInfoRules: { }
})
const data = reactive({
    personBesicInfo: {}  
})

defineExpose({ ruleFormRef })  // 第五步:通过defineExpose,将需要的变量与方法都暴露出去
</script>

这里解释一下:
使用<script setup> ,是默认关闭的,是一个闭环


完成校验动作
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容