Vue表单验证通过后跳转感谢页问题求助
解决表单验证通过后无法跳转至感谢页的问题
你的代码存在两个核心问题导致无法跳转至Greetings组件:
- 虽已导入
Greetings组件,但未在模板中渲染它,也没有控制其显示/隐藏的状态变量 fetch请求逻辑错误:无论请求成功与否,都只会弹出错误提示,未处理成功后的跳转逻辑
以下是具体修复步骤:
步骤1:添加控制感谢页显示的状态变量
在<script setup>中新增一个响应式变量,标记表单是否提交成功:
const isSubmitted = ref(false)
步骤2:在模板中切换表单与感谢页
修改<template>部分,用v-if/v-else控制显示表单或感谢页组件:
<template> <!-- 表单未提交成功时显示表单 --> <form @submit.prevent="send" v-if="!isSubmitted"> <h1>Information</h1> <label for="alternativ">Your choice</label> <select id="alternativ" v-model="formData.subject"> <option v-for="subject in subjects" :value="subject.value">{{ subject.label }}</option> </select> <div v-if="formData.subject !== 'support'"> <label for="name">Name</label> <input id="name" v-model="formData.name"> <label for="phone">Phone</label> <input id="phone" v-model="formData.phone" type="tel" maxlength="10"> <p v-for="error in errors" class="error">{{ error.message }}</p> <textarea v-if="formData.subject === 'question'" id="message" v-model="formData.message" placeholder="Write your message..."></textarea> <button type="submit">Send</button> </div> <p v-if="formData.subject === 'support'">Technical support is performed by our expert in the chat.</p> <button v-if="formData.subject === 'support'" type="submit">Open support</button> </form> <!-- 表单提交成功后显示感谢页 --> <Greetings v-else /> </template>
步骤3:修正fetch请求逻辑
当前then回调不管响应状态都弹出错误,需先判断请求是否成功(response.ok),成功则切换到感谢页,失败再提示错误:
const send = (e) => { const isFormValid = validate() console.log(isFormValid) if (isFormValid) { // 处理support类型的提交(可选,根据需求调整) if (formData.subject === 'support') { isSubmitted.value = true return } fetch('URL', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) // 必须转为JSON字符串,否则服务器无法解析 }) .then(response => { if (response.ok) { // 请求成功,切换到感谢页 isSubmitted.value = true } else { alert(`Sorry, something went wrong! Status: ${response.status}`); console.log(response); } }) .catch(err => { console.log(err); alert('Network error occurred, please try again later.'); }) } }
注意:原代码中
body: formData是错误写法,fetch提交JSON数据必须用JSON.stringify()转换对象。
内容的提问来源于stack exchange,提问作者Jose
相关产品推荐
相关产品推荐

