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>
相关推荐
金融小师妹16 小时前
基于多源政策信号解析与量化因子的“12月降息预期降温”重构及黄金敏感性分析
人工智能·深度学习·1024程序员节
GIS数据转换器20 小时前
基于GIS的智慧旅游调度指挥平台
运维·人工智能·物联网·无人机·旅游·1024程序员节
南方的狮子先生1 天前
【C++】C++文件读写
java·开发语言·数据结构·c++·算法·1024程序员节
Neil今天也要学习2 天前
永磁同步电机无速度算法--基于三阶LESO的反电动势观测器
算法·1024程序员节
开开心心_Every2 天前
专业视频修复软件,简单操作效果好
学习·elasticsearch·pdf·excel·音视频·memcache·1024程序员节
liu****3 天前
16.udp_socket(三)
linux·开发语言·数据结构·c++·1024程序员节
草莓熊Lotso3 天前
《算法闯关指南:优选算法--位运算》--38.消失的两个数字
服务器·c++·算法·1024程序员节
unable code4 天前
攻防世界-Misc-can_has_stdio?
网络安全·ctf·misc·1024程序员节
思茂信息4 天前
CST License(Flexnet)设置与问题处理方法
服务器·网络·单片机·3d·php·1024程序员节·cst
2301_797892834 天前
论文阅读:《Hypergraph Motif Representation Learning》
论文阅读·1024程序员节