Form submission
Handle a form's submit event in Vue and stop the browser from reloading the page.
In this page:
Syntax
<form @submit.prevent="submitHandler">
<input v-model="field">
<button type="submit">Send</button>
</form>
Form submission
Listen with @submit.prevent so the default page reload is cancelled, then read the bound data and send it, for example with fetch. Track loading and error states in data to give feedback. Reset fields after a successful submission.
Note:
Use @submit.prevent on the form, not @click on the button, so pressing Enter works too.
Example: Form submission
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<form @submit.prevent="submit">
<input v-model="name" required>
<button :disabled="sending">{{ sending ? "Sending..." : "Send" }}</button>
</form>
<p>{{ result }}</p>
</div>
<script>
Vue.createApp({
data() { return { name: "Ada", sending: false, result: "" }; },
methods: {
async submit() {
this.sending = true;
await new Promise((r) => setTimeout(r, 10)); // pretend network call
this.result = "Saved " + this.name;
this.sending = false;
},
},
}).mount("#app");
document.querySelector("form").dispatchEvent(new window.Event("submit", { cancelable: true }));
setTimeout(() => console.log(document.querySelector("p").textContent), 100);
</script>
</body>
</html>
<!-- Output:
Rendered: SendSaved Ada
console: Saved Ada
-->
Live Example
Related Topics
Common Mistakes
- Forgetting .prevent
- Using a click handler instead of submit
- Not showing loading or error states
Chapter Summary
- @submit.prevent handles the form
- Read data from v-model bindings
- Show loading and error states
- Reset fields after success
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: