vue3+vant4父组件点击提交并校验子组件form表单

先看效果

代码如下

父组件

复制代码
<template>
  <ChildForm ref="childFormRef" />
  <button @click="validateForm">校验表单</button>
</template>
<script setup>
import { ref } from 'vue';
import ChildForm from './ChildForm.vue';
const childFormRef = ref(null);
const validateForm = async () => {
  if (childFormRef.value) {
    try {
      const isValid = await childFormRef.value.validate();
      console.log('Form valid:', isValid);
    } catch (error) {
      console.error('Validation error:', error);
    }
  }
};
</script>

子组件

复制代码
<!-- ChildForm.vue -->
<template>
    <van-form ref="formRef">
      <!-- 表单项 -->
      <van-field label="账号" name="账号" v-model="pageList.fieldValue" :rules="rules" />
      <van-field
      v-model="pageList.password"
      label="密码"
      name="密码"
      type="password"
      placeholder="请输入密码"
      :rules="[{ required: true, message: '请输入密码' }]"
    />
    </van-form>
  </template>
  <script setup>
  import { ref, defineExpose } from 'vue';
  const formRef = ref(null);
  let pageList = ref({
    fieldValue:'',
    password:'',
  })
  const rules = ref([
    { required: true, message: 'This field is required' }
  ]);
  
  const validate = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validate();
        return true;
      } catch (error) {
        return false;
      }
    }
    return false;
  };
  defineExpose({ validate });
  </script>

父组件通过ref获取子组件的引用,在父组件的点击事件中调用子组件的validate方法进行表单验证,如果验证通过则执行提交逻辑。子组件通过defineExpose暴露其validate方法给父组件使用。这样父组件就可以通过childForm.value.validate调用子组件的验证方法了。

相关推荐
恋猫de小郭33 分钟前
Flutter 设计包解耦新进展,material_ui 和 cupertino_ui 发布预告
android·前端·flutter
linux_cfan1 小时前
[2026深度评测] 打造“抖音级”丝滑体验:Web直播播放器选型与低延迟实践
前端·javascript·html5
天天向上的鹿茸1 小时前
前端适配方案
前端·javascript
We་ct1 小时前
LeetCode 226. 翻转二叉树:两种解法(递归+迭代)详解
前端·算法·leetcode·链表·typescript
叫我一声阿雷吧1 小时前
JS实现无限滚动加载列表|适配多端+性能优化【附完整可复用源码】
开发语言·javascript·性能优化
哆啦A梦15882 小时前
Vue3魔法手册 作者 张天禹 013_pinia
前端·vue.js·typescript
哆啦A梦15882 小时前
Vue3魔法手册 作者 张天禹 014_组件通信
前端·vue.js·typescript
木斯佳2 小时前
前端八股文面经大全:有赞前端一面二面HR面(2026-1-13)·面经深度解析
前端·状态模式
VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue养老院管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
码云数智-园园2 小时前
Vue 3 + TypeScript 企业级项目架构实战:从0到1打造可维护的前端工程体系
前端·vue.js·typescript