How to Handle Form Submit in Vue: Simple Fix and Best Practices
@submit.prevent event listener on the <form> element and linking it to a method that processes the data. Use @submit.prevent to stop the page from reloading and run your custom submit logic instead.Why This Happens
When you add a submit event on a form without preventing the default behavior, the browser reloads the page. This stops your Vue method from running properly, causing the form data to be lost and no action to happen.
<template> <form @submit="submitForm"> <input v-model="name" placeholder="Enter name" /> <button type="submit">Submit</button> </form> </template> <script setup> import { ref } from 'vue' const name = ref('') function submitForm(event) { event.preventDefault() alert(`Name submitted: ${name.value}`) } </script>
The Fix
Add .prevent modifier to the @submit event to stop the page reload. This lets Vue run your submit method and handle the form data as you want.
<template> <form @submit.prevent="submitForm"> <input v-model="name" placeholder="Enter name" /> <button type="submit">Submit</button> </form> </template> <script setup> import { ref } from 'vue' const name = ref('') function submitForm() { alert(`Name submitted: ${name.value}`) } </script>
Prevention
Always use @submit.prevent on forms to stop default reload behavior. Keep your form logic inside methods and use v-model for input binding. Use Vue DevTools to check event handling and test your forms interactively.
Linting tools like ESLint with Vue plugin can warn if you forget .prevent on form submits.
Related Errors
Sometimes developers forget to add type="submit" on buttons inside forms, so the submit event never triggers. Also, using @click on buttons without preventing default form submit can cause unexpected reloads.
Fix these by ensuring buttons meant to submit have type="submit" and use @submit.prevent on the form.
Key Takeaways
@submit.prevent on <form> to stop page reload and handle submit in Vue.v-model for easy data access in submit methods.submit inside forms to trigger submit events.