You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue模态框底部按钮中编程提交Vee Validate表单

问题描述

我有一个包含简单“修改密码”表单的Modal组件,提交按钮位于模态框的footer插槽,而表单在模态框的主体插槽内。请问点击footer中的Save按钮时,如何以编程方式提交该Vee Validate表单?

原代码

模板部分

<Modal
    v-if="changingPassword"
    title="Change Password"
    @close="() => (changingPassword = false)"
>
    <VForm class="form w-100" @submit="onFormSubmit" :validation-schema="login">
        <Field
            tabindex="2"
            class="form-control form-control-lg form-control-solid"
            type="password"
            name="password"
        />

        <Field
            tabindex="2"
            class="form-control form-control-lg form-control-solid"
            type="password"
            name="new-password"
            autocomplete="new-password"
        />

        <Field
            tabindex="2"
            class="form-control form-control-lg form-control-solid"
            type="password"
            name="confirm-password"
            autocomplete="off"
        />
    </VForm>
    <template #footer>
        <button @click="submitForm">Save</button>
    </template>
</Modal>

脚本部分

<script setup lang="ts">
function submitForm(e) {
     //Submit form here
}
</script>

解决方案

方法一:通过ref获取表单实例提交

  1. 给<VForm>添加ref标识:
<VForm ref="passwordForm" class="form w-100" @submit="onFormSubmit" :validation-schema="login">
  1. 在脚本中定义ref并实现提交逻辑:
<script setup lang="ts">
import { ref } from 'vue';

const passwordForm = ref(null);
const changingPassword = ref(false); // 假设该变量控制模态框显示

function submitForm() {
  // 调用表单实例的submit方法触发验证与提交
  passwordForm.value?.submit();
}

function onFormSubmit(values) {
  // 验证通过后执行实际的密码修改逻辑
  console.log('提交的表单数据:', values);
  // 完成后关闭模态框
  changingPassword.value = false;
}
</script>

方法二:使用Vee Validate的useForm组合式API(Vee Validate 4+适用)

  1. 引入useForm并创建表单实例:
<script setup lang="ts">
import { useForm } from 'vee-validate';

const changingPassword = ref(false);

// 创建表单实例并绑定验证规则
const { handleSubmit, submitForm } = useForm({
  validationSchema: login // 传入你的验证schema
});

// 处理验证通过后的提交逻辑
const onFormSubmit = handleSubmit((values) => {
  console.log('提交的表单数据:', values);
  changingPassword.value = false;
});
</script>
  1. 调整模板中的表单与按钮:
<VForm class="form w-100" @submit="onFormSubmit">
  <!-- 表单字段保持不变 -->
</VForm>
<template #footer>
  <!-- 直接调用useForm返回的submitForm方法 -->
  <button @click="submitForm">Save</button>
</template>

注意事项

  • 若使用ref方法,需确保<VForm>实例已挂载,用可选链?.可避免未挂载时的报错。
  • Vee Validate 4+更推荐使用组合式API,逻辑更集中且灵活。
  • onFormSubmit仅在表单验证全部通过后触发,可在此处调用后端接口完成密码修改。

内容的提问来源于stack exchange,提问作者Bernard Borg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:45:57