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>
相关推荐
深蓝易网20 小时前
探寻制造型企业MES管理系统:功能、架构与应用全解析
大数据·运维·人工智能·架构·制造·1024程序员节
Lenyiin6 天前
2848、与车相交的点
c++·算法·leetcode·1024程序员节
earthzhang202112 天前
《深入浅出HTTPS》读书笔记(31):HTTPS和TLS/SSL
开发语言·网络·python·https·1024程序员节
不讲废话的小白14 天前
怎么样把pdf转成图片模式(不能复制文字)
pdf·1024程序员节
明明真系叻14 天前
2025.1.26机器学习笔记:C-RNN-GAN文献阅读
人工智能·笔记·深度学习·机器学习·生成对抗网络·1024程序员节
Joeysoda19 天前
Java数据结构 (从0构建链表(LinkedList))
java·linux·开发语言·数据结构·windows·链表·1024程序员节
清风-云烟21 天前
使用redis-cli命令实现redis crud操作
java·linux·数据库·redis·spring·缓存·1024程序员节
Joeysoda21 天前
Java数据结构 (链表反转(LinkedList----Leetcode206))
java·linux·开发语言·数据结构·链表·1024程序员节
比特在路上21 天前
StackOrQueueOJ3:用栈实现队列
c语言·开发语言·数据结构·1024程序员节
0xCC说逆向22 天前
Windows图形界面(GUI)-QT-C/C++ - Qt键盘与鼠标事件处理详解
c语言·开发语言·c++·windows·qt·win32·1024程序员节