Vue3 Fundamentals · Events & Forms

Handling form submission

Form submission

Handling form submission

A form is more than its fields: it has a moment when the user is done and asks to send everything at once. The browser's default is to reload the page and put the values in the URL, which throws away your component's state. You want to catch that moment instead.

A form fires a submit event when its submit button is pressed or the user presses Enter. Listen for it with @submit, and stop the reload with the .prevent modifier:

<script setup>
import { ref } from 'vue';

const name = ref('');
const submitted = ref('');

function onSubmit() {
  submitted.value = name.value;
}
</script>

<template>
  <form @submit.prevent="onSubmit">
    <input v-model="name" />
    <button type="submit">Submit</button>
  </form>
  <p>{{ submitted }}</p>
</template>

@submit.prevent runs your handler and cancels the browser's default. Your handler reads the bound refs and does the work — saving, validating, or, here, copying the name into submitted so the page can show it.

The submit button must have type="submit", and the form's @submit catches the event whether the button or Enter triggered it.

Your job is to handle a form's submit in App.vue.

Challenge

The form on the page never reads the name back. Export an App component from App.vue that renders a <form> with a text input bound with v-model, a submit button, and a <p>. Handle the form's submit so it copies the name into another ref, and render that ref in the paragraph.

The Test types Vue, submits the form, and expects the paragraph to read Vue. The starter never handles the submit, so the paragraph stays empty and the Test fails.

App.vue
<script setup>
import { ref } from 'vue';

const name = ref('');
const submitted = ref('');
</script>

<template>
  <form>
    <input v-model="name" />
    <button type="submit">Submit</button>
  </form>
  <p>{{ submitted }}</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.