How to Handle Form in Vue: Fix Common Issues and Best Practices
v-model to bind input values to data properties and listen to the submit event with @submit.prevent to process the form without page reload. This keeps the form reactive and easy to manage.Why This Happens
Often beginners try to handle form inputs without binding them properly or forget to prevent the default form submission, causing page reloads or unresponsive inputs.
This happens because Vue needs v-model to sync input values with data and @submit.prevent to stop the browser from refreshing the page on submit.
<template> <form @submit.prevent="submitForm"> <input type="text" name="username" /> <button type="submit">Submit</button> </form> </template> <script setup> function submitForm() { alert('Form submitted'); } </script>
The Fix
Use v-model on inputs to bind them to reactive data properties. Add @submit.prevent on the form to stop page reload and handle submission in a method.
<template> <form @submit.prevent="submitForm"> <input v-model="username" type="text" placeholder="Enter username" /> <button type="submit">Submit</button> </form> <p>Your username is: {{ username }}</p> </template> <script setup> import { ref } from 'vue' const username = ref('') function submitForm() { alert(`Form submitted with username: ${username.value}`) } </script>
Prevention
Always bind form inputs with v-model to keep data reactive. Use @submit.prevent on forms to prevent default reload. Validate inputs before processing. Use Vue DevTools to inspect reactive data during development.
Lint your code with Vue-specific rules to catch missing bindings or event handlers early.
Related Errors
Common related errors include:
- Input not updating data: missing
v-model - Form submits but page reloads: missing
@submit.prevent - Data not reactive: using plain variables instead of
reforreactive
Key Takeaways
v-model to bind form inputs to reactive data in Vue.@submit.prevent on forms to stop page reload on submit.