Vue 2/Vuetify表单必填项为空时如何阻止提交?
Vue2/Vuetify2 联系表单验证修复及提交后清空方案
你的核心问题是提交时未触发Vuetify表单的内置验证,直接跳过校验发送了请求,手动验证逻辑又放在axios的catch块里(只有请求失败才会执行),导致无效表单依然能提交。以下是具体修复方案:
1. 关键修改点
步骤1:给表单添加ref标识
给<v-form>添加ref属性,方便调用Vuetify内置的表单验证方法:
<v-form v-on:submit="handleSubmit" v-model="valid" ref="contactForm">
步骤2:重构提交逻辑,先验证再请求
修改handleSubmit方法,先触发全表单验证,验证通过后再发送请求,成功后清空表单:
handleSubmit: async function (e) { e.preventDefault(); // 触发所有字段的验证,返回验证结果 const isFormValid = await this.$refs.contactForm.validate(); if (!isFormValid) { // 验证不通过,直接终止提交 return; } try { const response = await axios.post( "https://api-next.impact-hq.org/api/contacts", { data: { name: this.name, email: this.email, subject: this.subject, message: this.message, }, } ); console.log(response); // 提交成功后执行表单重置 this.resetForm(); // 可选:添加提交成功提示 this.$notify({ type: 'success', text: '表单提交成功!' }); // 可选:关闭弹窗 this.show = false; } catch (error) { // 处理请求失败(如网络错误、Strapi返回的错误) console.error('提交失败:', error); this.$notify({ type: 'error', text: '提交失败,请稍后重试!' }); } }, // 新增表单重置方法 resetForm() { // 清空所有字段值 this.name = ''; this.email = ''; this.subject = ''; this.message = ''; // 重置表单的验证状态(清除字段错误提示) this.$refs.contactForm.reset(); // 清空自定义错误数组 this.errors = []; }
步骤3:移除无效的手动验证代码
删除catch块里的手动字段校验逻辑,因为Vuetify的内置验证已经会在每个字段上显示错误提示,且提交前已经做了全表单校验,不会走到这一步。
2. 完整修改后代码
Template部分
<template> <v-dialog persistent v-model="show" max-width="650px"> <v-card class="px-9 py-5" color="#EEF8FF"> <div class="d-flex justify-end"> <div style="color: #020659" class="d-flex align-center cursor-pointer p-5 mb-5" @click.stop="show = false" > Close <v-icon color="#020659" class="">mdi-close</v-icon> </div> </div> <v-card class="px-11 no-bottom-border" elevation="1"> <v-form v-on:submit="handleSubmit" v-model="valid" ref="contactForm"> <!-- 全局错误提示(可选保留) --> <div class="pt-3" v-if="errors.length"> <b>Please correct the following error(s):</b> <ul> <li v-for="error in errors" :key="error">{{ error }}</li> </ul> </div> <v-row> <v-col cols="12" class=""> <h2 class="themepurple my-3">Contact Us</h2> </v-col> </v-row> <v-card-text> <v-row> <v-col cols="6"> <v-text-field color="#020659" label="Name*" required name="name" v-model="name" :rules="nameRules" ></v-text-field> </v-col> <v-col cols="6"> <v-text-field color="#020659" label="E-Mail*" required name="email" v-model="email" type="email" :rules="emailRules" ></v-text-field> </v-col> </v-row> <v-row> <v-col> <v-select v-model="subject" required name="subject" label="Subject*" :items="[ 'Account Creation or Login Issue', 'Not a 501c3 - Requesting an Exception', 'Can\'t Find the Information I am Looking For', 'Suggestion for Future Content', 'Website Issue', 'Service Directory Edits', 'Other', ]" variant="underlined" color="#020659" :rules="subjectRules" ></v-select> </v-col> </v-row> <v-row> <v-col> <v-textarea v-model="message" name="message" required color="#020659" label="How Can We Help?*" :rules="messageRules" > </v-textarea> </v-col> </v-row> <v-row> <v-col> <v-btn type="submit" block class="mt-2 submit-button"> Submit</v-btn > </v-col> </v-row> </v-card-text> </v-form> </v-card> </v-card> </v-dialog> </template>
Script部分
<script> import axios from "axios"; export default { name: "ContactUs", props: { value: Boolean, }, data() { return { valid: false, name: "", nameRules: [(v) => !!v || "Name is required"], email: "", emailRules: [ (v) => !!v || "E-mail is required", (v) => /.+@.+/.test(v) || "E-mail must be valid", ], subject: "", subjectRules: [(v) => !!v || "Subject is required"], message: "", messageRules: [(v) => !!v || "Message is required"], errors: [], }; }, methods: { handleSubmit: async function (e) { e.preventDefault(); const isFormValid = await this.$refs.contactForm.validate(); if (!isFormValid) return; try { const response = await axios.post( "https://api-next.impact-hq.org/api/contacts", { data: { name: this.name, email: this.email, subject: this.subject, message: this.message, }, } ); console.log(response); this.resetForm(); this.$notify({ type: 'success', text: '表单提交成功!' }); this.show = false; } catch (error) { console.error('提交失败:', error); this.$notify({ type: 'error', text: '提交失败,请稍后重试!' }); } }, resetForm() { this.name = ''; this.email = ''; this.subject = ''; this.message = ''; this.$refs.contactForm.reset(); this.errors = []; } }, computed: { show: { get() { return this.value; }, set(value) { this.$emit("input", value); }, }, }, }; </script>
内容的提问来源于stack exchange,提问作者M. Straw
相关产品推荐
相关产品推荐

