当前位置: 首页 > article >正文

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

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

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

子组件代码

<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>

父组件接收参数

</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>

http://www.kler.cn/news/368396.html

相关文章:

  • Java 基于 poi 和 itextpdf 实现 excel 转 pdf
  • MySql中表的复合查询
  • 来源爬虫程序调研报告
  • 嵌入式Linux的AXI平台(platform)驱动教程
  • 2024年CentOS镜像下载地址,包括CentOS官网、国内镜像下载,超详细也
  • 【数学二】多元函数积分学-重积分-二重积分定义、性质、计算
  • Linux系统下串口AT指令控制EC20连接华为云物联网平台
  • 使用 docker 的方式部署 NFS server 提供文件共享能力
  • springboot066人事系统(论文+源码)_kaic
  • 【动态规划】力扣198.打家劫舍
  • 【设计模式系列】迭代器模式(七)
  • 【大数据学习 | kafka】kafka的组件架构
  • 程序测试工具Burp Suite 表格排序和中继器的性能改进
  • golang正则表达式的使用及举例
  • NAT技术和代理服务器
  • Docker 下备份恢复oracle
  • FineReport 分栏报表
  • uniapp使用uni-push模拟推送
  • MySQL 【正则表达式】函数大全
  • 如何用Jmeter做性能测试
  • 构建ECMAScript标准
  • 论文略读Fewer Truncations Improve Language Modeling
  • 玩转springboot之springboot属性绑定原理
  • ESP32-S3-DevKitC-1开发记录帖(2)——与MPU6050一起部署动作识别神经网络
  • 单链表总结
  • Zig 语言通用代码生成器:逻辑,冒烟测试版发布二