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调用子组件的验证方法了。

相关推荐
我命由我1234510 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
Hopebearer_11 小时前
页面突然只剩 DOM?一次静态资源版本错配排查
前端·部署
抱抱宝11 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
东风破_12 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
用户9385156350712 小时前
Next.js 笔记系统(二):Redis 数据服务与侧边栏组件拆分实战
javascript·全栈
java1234_小锋13 小时前
Vue3专题 - 组件基础
vue.js·vite
圣殿骑士-Khtangc13 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
BigTopOne14 小时前
【ijkplayer】 硬解码流程
前端
kyriewen14 小时前
DeepSeek Harness开源第一天我就上手了——和Claude Code的差距比想象中大
前端·ai编程·deepseek
捡田螺的小男孩15 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员