0
0
VueDebug / FixBeginner · 4 min read

How to Handle Form Submit in Vue: Simple Fix and Best Practices

In Vue, handle form submission by adding a @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.

vue
<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>
Output
Page reloads on submit and alert never shows.
🔧

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.

vue
<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>
Output
Alert shows 'Name submitted: [entered name]' and page does not reload.
🛡️

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

Use @submit.prevent on <form> to stop page reload and handle submit in Vue.
Bind form inputs with v-model for easy data access in submit methods.
Always set button type to submit inside forms to trigger submit events.
Use Vue DevTools and ESLint Vue plugin to catch common form handling mistakes early.