需求:父組件點(diǎn)擊保存按鈕時嘀掸,對多個子組件中的表單進(jìn)行校驗(yàn)
解決方法:
父組件
<child
ref="childRef" // 第一步:給每個子組件標(biāo)簽添加ref
>
</child>
<script setup>
const childRef= ref() // 第二步:聲明常量
const save = ()=>{ // 保存事件
const child= abilityRuleFormRef.value.ruleFormRef // 第六步:獲取子組件暴露出的變量
const childRES = new Promise((resolve, reject) => { // 創(chuàng)建Promise實(shí)例紫岩,為多個組件校驗(yàn)使用
child.validate((valid, fields) => {
if (valid) {
resolve()
} else {
Object.keys(fields).forEach((v, index) => { // 第七步:通過scrollToField()方法完成校驗(yàn)定位
if (index === 0) {
const propName = fields[v][0].field
child.scrollToField(propName)
}
})
reject()
}
})
})
// 多個子組件校驗(yàn)
Promise.all([formElRES, abilityRES, developRES, reprotMessageRES])
.then(()=>{
console.log('這里完成接口請求')
})
.catch(err => {
ElMessage({
message: '必填項(xiàng)不能為空',
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({ // 校驗(yàn)規(guī)則
baseInfoRules: { }
})
const data = reactive({
personBesicInfo: {}
})
defineExpose({ ruleFormRef }) // 第五步:通過defineExpose,將需要的變量與方法都暴露出去
</script>
這里解釋一下:
使用<script setup> 睬塌,是默認(rèn)關(guān)閉的泉蝌,是一個閉環(huán)