v-model on Text Inputs
Shelf's Add Book form has a title box and a notes area. As the user types, your state must hold what they typed; when you reset the form, the boxes must empty. Wiring a value binding and an input listener on every field gets old quickly. v-model does both in one attribute.
The rule
v-model is
:valuein plus@inputout: two-way, in one word.
<script setup>
import { ref } from 'vue'
const title = ref('')
const notes = ref('')
function reset() {
title.value = ''
notes.value = ''
}
</script>
<template>
<input v-model="title" placeholder="Title" />
<textarea v-model="notes"></textarea>
<p>Preview: {{ title || 'Untitled' }}</p>
<button @click="reset">Clear</button>
</template>Type "Dune" and title holds 'Dune', so the preview updates as you type. Click Clear and both boxes empty, because the state flows back into them. On a text input, v-model="title" is shorthand for:
<input :value="title" @input="title = $event.target.value" />:value="title"pushes state into the box (state → page).@input="..."copies each keystroke back into state (page → state).
Things that follow from this:
- State is the single source of truth.
v-modelignores thevalueattribute written in HTML.<input v-model="title" value="Untitled">starts empty iftitleis''. Put starting values in the ref:ref('Untitled'). - Textareas use v-model too.
<textarea>{{ notes }}</textarea>does not work for two-way binding; write<textarea v-model="notes">. - The bound thing must be writable.
v-modelneeds something it can assign to, such as a ref or an object property.v-model="title.toUpperCase()"makes no sense, since you cannot assign to a function call. Binding a prop directly is also wrong, since props are read-only; the component v-model lesson shows the right way. - Values are strings. Whatever the user types arrives as text, even in a box for page counts. The Modifiers lesson handles that.