当前位置:首页 » 《关注互联网》 » 正文

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

24 人参与  2024年10月28日 12:41  分类 : 《关注互联网》  评论

点击全文阅读


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://zhangshiyu.com/post/178940.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1