vue3父组件控制子组件表单验证及获取子组件数值方法

1、关键部分的代码如下,我努力交代清楚了,希望能让大家看懂。

javascript 复制代码
<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、顺便记录下父组件获取子组件数值的写法,和获取当前日期的函数。

子组件代码

javascript 复制代码
<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>

父组件接收参数

javascript 复制代码
</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>
相关推荐
CoderYanger2 小时前
贪心算法:7.最长连续递增序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger3 小时前
贪心算法:6.递增的三元子序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger3 小时前
贪心算法:1.柠檬水找零
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger3 小时前
贪心算法:4.摆动序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 小时前
贪心算法:2.将数组和减半的最少操作次数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger6 小时前
贪心算法:8.买卖股票的最佳时机
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger6 小时前
贪心算法:3.最大数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger6 小时前
贪心算法:5.最长递增子序列
java·算法·leetcode·贪心算法·1024程序员节
liguojun20251 天前
智慧破局:重构体育场馆的运营与体验新生态
java·大数据·人工智能·物联网·重构·1024程序员节
Yupureki2 天前
《算法竞赛从入门到国奖》算法基础:入门篇-前缀和
c语言·数据结构·c++·算法·1024程序员节