1、关键部分的代码如下,我努力交代清楚了,希望能让大家看懂。
<template><KeepAlive> <component ref="comp" :is="compNames[steps[compIndex].comp]" /></KeepAlive><el-button @click="prevBtn" v-show="compIndex">上一步</el-button><el-button type="primary" @click="nextBtn">{{compIndex ? '提交': '下一步'}}</el-button></template><script setup lang="ts">//引入两个子组件import onefrom './onefrom.vue'import twoForm from './twoForm.vue'//子组件切换相关参数const steps = [{title:'111',comp:'one',ref:'oneForm'},{title:'222',comp:'two',ref:'twoForm'}]//当前组件索引const compIndex = ref(0)//子组件名type compName = { [key:string]:any}const compNames = shallowReactive<compName>({oneForm,twoForm})//组件设置ref="comp"const comp = ref(null); //点击按钮验证子组件表单const prevBtn = () => { compIndex.value=0}const nextBtn = () => { if (compIndex.value == 0 && comp.value.$refs.formRef) { comp.value.$refs.formRef.validate((valid) => { if (valid) { compIndex.value = 1 //表单验证通过后切换到子组件twoForm } }); }}
2、顺便记录下父组件获取子组件数值的写法,和获取当前日期的函数。
子组件代码
<template><el-form-item label="创建时间"> <el-date-picker v-model="currentDate" type="date"/></el-form-item></template><script setup lang="ts">//获取当前日期let currentDate = computed<string>(() => { let currentDate = new Date(); let year = currentDate.getFullYear(); let month = currentDate.getMonth() + 1; let day = currentDate.getDate(); return year + '-' + month + '-' + day;});// 表单参数const initFormData = reactive<formulaForm>({ id: null, name: undefined, createTime: currentDate.value})//将表单参数暴露给父组件defineExpose({ initFormData})</script>
父组件接收参数
</template><component ref="comp" :is="compNames[steps[compIndex].comp]" /><el-button @click="Btn">获取参数</el-button></template><script setup lang="ts">const Btn = () => { console.log(comp.value.initFormData)}</script>