Submitting a Vue Form
Submitting a form sends its answers in one step. A form in Vue handles the submit with a function instead of loading a new page.
Listen for submit
The form runs send when it is sent.
<form @submit.prevent="send">
<button>Send</button>
</form>The send function
The function marks the form as sent.
function send() {
sent.value = true
}Show a thanks message
The message shows only after the form is sent.
<p v-if="sent">Thanks, {{ name }}!</p>Example
<script setup>
import { ref } from 'vue'
const name = ref('')
const sent = ref(false)
function send() {
sent.value = true
}
</script>
<template>
<div>
<form @submit.prevent="send">
<label>Name <input v-model="name"></label>
<button>Send</button>
</form>
<p v-if="sent">Thanks, {{ name }}!</p>
</div>
</template>Key points
- A form is a group of inputs that belong together, like the boxes on a sign-up page.
- @submit listens for the submit event, which fires when the form is sent.
- .prevent stops the browser from loading a new page after the submit.
- The submit function runs when the form is sent, and it can read every ref in the form.
- A ref can mark the form as sent, so the page can show a thanks message.
In this example, name is a ref that starts as an empty string. sent is a ref that starts as false. The form runs send when it is sent, and .prevent stops a new page from loading. send sets sent to true. The thanks message shows only when sent is true. The page starts with no message. Sending the form with Ada in the box shows Thanks, Ada!.
Note
The button inside the form sends the form when it is clicked.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does the form use @submit.prevent?