Text Fields and v-model

Forms are how customers tell an app what they want: they type a name, choose a drink, tick a box. In this lesson, you'll build the order form of Corner Café, one kind of field at a time, and then send it.

With what you know from the lesson State and Events, you could already keep the text of a field in a ref: :value puts the ref into the field, and @input puts each change of the field's text back into the ref:

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

const name = ref("");

function updateName(event) {
    name.value = event.target.value;
}
</script>

<template>
    <input :value="name" @input="updateName">
    <p>Order for {{ name }}</p>
</template>

A form has many fields, and writing both halves for each of them gets long. The directive v-model does both:

<input v-model="name">
<p>Order for {{ name }}</p>

No function needed. Type Anna, and name is "Anna", so the paragraph shows Order for Anna. It also works the other way: when the script changes the ref, say with name.value = "", the field shows the new value, here nothing. The field and the ref always hold the same text, which is why this is called two-way binding.

A textarea, a field for longer text on several lines, works the same way: <textarea v-model="note"></textarea>. Don't put {{ note }} between its tags: that only puts the note into the field when the page starts, and what's typed never gets into the ref.

Typical mistakes:

  • v-model on a variable that isn't a ref. With const name = "";, the page doesn't run, and the red bar says v-model cannot be used on a const binding because it is not writable. With let, you can type, but the page doesn't change, as with a plain let in the lesson State and Events.
  • v-model="name.value". In the template, a ref is written without .value, and v-model is no exception. Typing then shows TypeError: Cannot create property 'value' on string '' in the console.

Instructions

  1. Connect the text field #name with the ref name using v-model. Type your name: the order shows it while you type.

  2. Connect the textarea #note with the ref note the same way.

  3. Under the order, add a button Clear that empties both fields. Its function only needs to change the refs.