Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 87 ยท Forms and User Input

Building Forms

Build complete forms in Vue 3 - a reactive form object, @submit.prevent, reset that really resets, disabled states while sending, accessible labels and live status messages.

v-model connects one field to one piece of state. A real form is more than that: it has several fields, a submit action, a way to start over, a moment where it is busy talking to a server, and users who rely on keyboards or screen readers. This lesson puts those pieces together into forms you can reuse as a pattern.

The idea that makes Vue forms pleasant is the same as in the rest of the framework. The form is just state. If the values live in one reactive object, then submitting is reading that object, resetting is writing to it, and a disabled button is a calculation on top of it. You never have to ask the DOM what the user typed.

One reactive object for the whole form

Instead of one ref per field, keep a single reactive object and bind every input to a property of it. Each input needs only v-model="form.field".

Two habits keep the form tidy:

  • Write the starting values in a factory function (emptyForm()), not a constant object. Every call returns a fresh object, so you can reset without any shared leftovers (an array field, for example, would otherwise be shared between resets).
  • Listen to submit with the .prevent modifier. @submit.prevent="submit" calls event.preventDefault() for you, so the browser does not navigate away. Details of modifiers are in handling events.

The sandbox must never post to a real server, so these examples print the submitted data on the page. In an application you would send it with fetch at the same spot.

A sign-up form with submit and reset

Type a name, press Create account, and the submitted copy appears. Notice { ...form }: it takes a plain snapshot, so later typing does not change what was "sent". Press Reset and everything returns to the starting values, including the select and the checkbox.

Why reset needs @reset.prevent

A <button type="reset"> triggers the browser's own reset, which puts every input back to the value written in the HTML. Vue does not hear about that (no input event fires), so the DOM and your state would disagree. The fix is the line above: stop the native reset with .prevent, then reset the state and let Vue re-render the inputs. Whenever you see a form whose fields and state drift apart, suspect a native reset.

flowchart LR
  A["User edits a field"] --> B["v-model updates form.field"]
  B --> C["Template re-renders"]
  D["Submit button or Enter"] --> E["@submit.prevent runs submit()"]
  E --> F["Read form, send or print data"]
  G["Reset button"] --> H["@reset.prevent runs reset()"]
  H --> I["Object.assign(form, emptyForm())"]
  I --> C

The form object is the hub: typing writes to it, submit reads from it, reset overwrites it, and the template always follows.

Use Object.assign(form, emptyForm()) to reset a reactive object. Writing form = emptyForm() would not work, because you would replace the variable instead of changing the reactive proxy that the template is watching. The reactivity pitfalls lesson explains this trap.

Use a real form and a submit button

It is tempting to put @click on a plain button. Prefer <form @submit.prevent> with a type="submit" button, for three reasons:

  • Pressing Enter in a text field submits the form with no extra code.
  • Assistive technology announces the region as a form.
  • The browser's built-in constraint checks (required, type="email", minlength) run before your handler is called, and their messages come for free.

One gotcha: a <button> inside a form is a submit button by default. A button that only opens a menu or removes a row must say type="button", or clicking it will submit the form.

If you replace the browser's validation bubbles with your own messages (the next lesson, form validation, does exactly that), add novalidate to the <form> so the browser does not show its bubbles on top of yours.

Disabled states and busy forms

Real submissions take time. While the request is in flight the user should not be able to edit fields or click twice. Because the status is state, you only need one variable and a few bindings:

  • status holds "idle", "sending" or "done".
  • :disabled="status === 'sending'" on the button blocks double clicks.
  • A <fieldset :disabled="..."> disables every control inside it with one binding, which is far less work than binding each input.
  • A computed decides whether the form is ready to submit.

The example fakes a slow server with a promise that resolves after 800 milliseconds.

Disabled while sending, with a live status

The button stays disabled until the email contains an @ and the message is not empty. While sending, the whole fieldset greys out, then the message clears so the user can write another. The if (!canSubmit.value) return; guard in submit matters too: a disabled button is only a hint for the user, and the handler can also be reached by other paths (a script calling requestSubmit(), for example), so it must protect itself.

A disabled control is not submitted with native form data and cannot receive focus. That is what you want while a request is running, but it is a poor way to say "this field is invalid". Disabling a submit button forever, with no explanation, leaves users guessing. Prefer showing a message that says what is missing.

Accessible labels and messages

Forms are where accessibility mistakes cost the most. A few rules cover most of the ground:

  • Every control needs a label. Either wrap the input in <label>, or give the input an id and the label a matching for. A placeholder is not a label: it disappears as soon as you type.
  • Group related controls. Radio buttons and checkbox sets belong in a <fieldset> with a <legend>.
  • Say what you expect. Add autocomplete values (name, email, new-password) so browsers and password managers can help, and type values so mobile keyboards fit the content.
  • Announce changes. Status text that appears after an action should live in an element with role="status" (or aria-live="polite"). The element must exist in the page before its text changes, which is why the example keeps the <p> always present and swaps what is inside it.
  • Connect errors to fields. You will use :aria-invalid and aria-describedby for that in the next lesson. Other bindings are in binding attributes, and the topic gets its own treatment in accessibility in Vue.

Putting it together: a checklist

When you build a form in Vue, run through this list:

  1. One reactive object (or a few refs) holds all values, created by a factory function.
  2. <form @submit.prevent="submit"> with a type="submit" button; other buttons have type="button".
  3. Reset overwrites state and uses @reset.prevent so the DOM and state stay in step.
  4. A status variable and a computed canSubmit drive disabled states.
  5. Labels, autocomplete, and a live status message.
  6. Submit sends a copy of the data ({ ...form }), never the live proxy you keep editing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @submit.prevent do on a <form>?

    The .prevent modifier is shorthand for calling event.preventDefault() inside the handler. Without it the browser would perform its default form submission and leave the page.
  2. 2. Why use @reset.prevent together with a reset method that overwrites the state?

    The browser's reset restores the values written in the HTML and fires no input event, so v-model never learns about it. Resetting the state instead lets Vue re-render the inputs correctly.
  3. 3. How do you reset a reactive() form object to its starting values?

    Assigning to the variable replaces it and breaks the link with the template. Object.assign writes the new values onto the same reactive proxy, so the template updates.
  4. 4. What is the simplest way to disable all inputs of a form section while a request runs?

    A disabled fieldset disables every form control inside it, so one binding is enough.
  5. 5. Which is the best way to give an input an accessible name?

    A label is always visible, clickable and announced by screen readers. A placeholder disappears when the user types and is not a reliable label.

Summary

  • Keep the whole form in one reactive object built by a factory function, and bind inputs with v-model="form.field".
  • Use <form @submit.prevent="submit"> and a real submit button; other buttons in the form need type="button".
  • Reset by overwriting state with Object.assign and cancel the native reset with @reset.prevent.
  • Drive busy and disabled states from a status variable and a computed; a disabled <fieldset> disables everything inside it.
  • Always label controls, add autocomplete, and announce status changes with role="status".
  • Send a copy of the data, and in the sandbox print it instead of posting it.

Next: Form Validation