vue3 设置动态 ref 并获取

需求是一个form表单切割成三部分,填完一部分可点击下一步继续填写下一部分,全部都完成后点击提交按钮,进行各部分的表单验证,如果验证没问题可提交。

以下代码没有满足我的需求,仅仅是获取到了子组件传来的值。

<template>
    <el-container class="bg-white">
        <el-header height="40px" class="AddHeader">
            <span v-for="(item,index) in steps" 
            	@click="changeComp(index)" 
            	:class="{'xxk-active':compIndex == index}">{{ item.title }}</span>
        </el-header>
        <el-main>
            <KeepAlive>
                <component 
                	:ref="(el: refItem) => setRefMap(el, steps[compIndex].comp)"
                	:is="compNames[steps[compIndex].comp]"/>
            </KeepAlive>
        </el-main>
        <el-footer height="32px">
            <div class="footerBtn el-button-long">
                <el-button @click="prevBtn" v-show="compIndex">上一步</el-button>
                <el-button type="primary" @click="nextBtn">
                	{{compIndex == 2 ? '提交': '下一步'}}</el-button>
            </div>
        </el-footer>
    </el-container>
</template>

<script setup lang="ts">
import GeneratedCode from './components/GeneratedCode.vue'
import Configuration from './components/Configuration.vue'
import Setting from './components/Setting.vue'

// 组件切换
const steps = [
    { title: 'oneForm', comp: 'GeneratedCode' },
    { title: 'twoForm', comp: 'Configuration'},
    { title: 'threeForm', comp: 'Setting'}]

// 当前组件index
const compIndex = ref(0)
type compName = {
    [key:string]:any
}
const compNames = shallowReactive<compName>({ GeneratedCode, Configuration, Setting })

//设置动态组件ref
const refMap: Record<string, refItem> = {}
type refItem = Element | ComponentPublicInstance | null
const setRefMap = (el: refItem, item: string ) => {
    el && (refMap[`${item}`] = el)
}
// 切换组件
const changeComp = (index: number) => {
    compIndex.value = index
}

// 上一步
const prevBtn = () => {
    compIndex.value -= 1 
}

// 下一步/提交按钮
const nextBtn = async () => {
    if (!(compIndex.value < 2 && (compIndex.value += 1))) {
        console.log(refMap['GeneratedCode'])
        console.log(refMap['Configuration'])
        console.log(refMap['Setting'])
    }
}

</script>
<style lang="scss" scoped>
.AddHeader{
    span{
        cursor: pointer;
    }
}
.xxk-active{
    color:#296EFF;
    font-size: 18px;
    font-weight: 600;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值