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>
相关推荐
Yangy_Jiaojiao2 天前
三维手眼标定
1024程序员节
guozhetao4 天前
【图论,拓扑排序】P1347 排序
数据结构·c++·python·算法·leetcode·图论·1024程序员节
lzb_kkk21 天前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
lzb_kkk1 个月前
【MFC】编辑框、下拉框、列表控件
c语言·开发语言·c++·mfc·1024程序员节
lzb_kkk1 个月前
【MFC】树控件的使用详解
开发语言·c++·windows·mfc·1024程序员节
SizeTheMoment2 个月前
List介绍
1024程序员节
开利网络2 个月前
产业互联网+三融战略:重构企业增长密码
大数据·运维·服务器·人工智能·重构·1024程序员节
wei_shuo2 个月前
从数据中台到数据飞轮:实现数据驱动的升级之路
1024程序员节·数据飞轮
玖剹3 个月前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节
jamison_14 个月前
文心一言与 DeepSeek 的竞争分析:技术先发优势为何未能转化为市场主导地位?
人工智能·ai·chatgpt·gpt-3·1024程序员节