Form input bindings with v-model
Two-way binding of native inputs, textareas, checkboxes, radios and selects with v-model, what it expands to, and the .lazy, .number and .trim modifiers.
Event handling and modifiersText interpolation and attribute binding
Form input bindings with v-model
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `v-model` is shorthand for binding a form control's value and listening for its change event. On a text input it expands to `:value` plus an `@input` handler that writes back.
- The property and event depend on the control: text inputs and textareas use `value` and `input`, checkboxes and radios use `checked` and `change`, and selects use `value` and `change`.
- Your JavaScript state is the source of truth. `v-model` ignores any initial `value`, `checked` or `selected` attribute in the template.
- A single checkbox binds a boolean (or custom `true-value` / `false-value`), several checkboxes bound to the same array collect the checked values, radios bind the selected value, and `<select multiple>` binds an array.
- `.lazy` syncs on `change` instead of every keystroke, `.number` converts the input with `parseFloat` when it can (and is applied automatically on `type="number"`), and `.trim` strips surrounding whitespace.
- During IME composition for languages like Chinese or Japanese, `v-model` waits for the composition to finish; listen to `@input` yourself if you need every intermediate value.
Keeping an input and state in sync
A form field holds a value the user can change, and your component holds state your code reads. For a form to work, those two must agree. When state changes, the field should show it. When the user types, state should update.
With what the previous lessons covered, you can already wire that up by hand: bind the value one way with :value, and listen for changes the other way with @input.
<script setup>
import { ref } from 'vue'
const name = ref('')
</script>
<template>
<input :value="name" @input="name = $event.target.value" />
<p>Hello, {{ name || 'stranger' }}</p>
</template>
That works, but it is the same two halves on every field in every form. v-model is the shorthand:
<input v-model="name" />
This is the “two-way binding” people mean when they talk about Vue forms. There is nothing magical about it: it is a one-way binding plus an event listener, generated for you. React has no shorthand for this; a controlled input writes both halves explicitly every time, as forms and controlled inputs shows.
State is the source of truth
v-model treats your JavaScript state as authoritative. Any value, checked or selected attribute you write in the template is ignored, because otherwise there would be two competing answers to “what is in this field?”. Set initial values where the state is declared:
<script setup>
import { ref } from 'vue'
const query = ref('shoes') // the box starts with "shoes"
</script>
<template>
<input v-model="query" value="ignored" />
</template>
v-model also works on nested properties, which is convenient for a form object. reactive(), used below, makes a whole object reactive and is covered with ref in ref and reactive:
<script setup>
import { reactive } from 'vue'
const review = reactive({ name: '', content: '', rating: null })
</script>
<template>
<input v-model="review.name" />
<textarea v-model="review.content"></textarea>
</template>
Note the textarea. Interpolation between its tags, <textarea>{{ text }}</textarea>, does not bind anything. Use v-model.
Each control speaks a different dialect
Form controls do not expose their value the same way. A text input has a value property and fires input on each keystroke. A checkbox has a checked property and fires change. v-model hides that from you by picking the right pair for each element:
| Element | Property bound | Event listened to |
|---|---|---|
<input type="text">, <textarea> |
value |
input |
<input type="checkbox">, <input type="radio"> |
checked |
change |
<select> |
value |
change |
Think of it as a universal power adapter: one plug on your side, the right prongs for each socket.
Checkboxes, radios and selects
A single checkbox binds a boolean:
<script setup>
import { ref } from 'vue'
const agreed = ref(false)
</script>
<template>
<label><input type="checkbox" v-model="agreed" /> I agree</label>
</template>
If the state should hold something other than true and false, set true-value and false-value, for example true-value="yes" false-value="no". They only affect your state, not what a native form submission sends, since browsers never submit unchecked boxes.
Several checkboxes bound to the same array collect the values of the checked ones:
<script setup>
import { ref } from 'vue'
const toppings = ref(['ham'])
</script>
<template>
<label><input type="checkbox" value="cheese" v-model="toppings" /> Cheese</label>
<label><input type="checkbox" value="ham" v-model="toppings" /> Ham</label>
<label><input type="checkbox" value="olives" v-model="toppings" /> Olives</label>
<p>{{ toppings.join(', ') }}</p>
</template>
Radios bound to the same state hold the value of whichever one is selected:
<label><input type="radio" value="card" v-model="payment" /> Card</label>
<label><input type="radio" value="paypal" v-model="payment" /> PayPal</label>
A <select> binds the selected option’s value, or an array of values with multiple. Options rendered from data combine naturally with v-for, and binding :value lets an option carry a number or even an object rather than a string:
<script setup>
import { ref } from 'vue'
const sizes = [
{ id: 1, label: 'Small' },
{ id: 2, label: 'Medium' },
{ id: 3, label: 'Large' },
]
const sizeId = ref('')
</script>
<template>
<select v-model="sizeId">
<option disabled value="">Choose a size</option>
<option v-for="size in sizes" :key="size.id" :value="size.id">
{{ size.label }}
</option>
</select>
</template>
That disabled empty option is not decoration. If the state matches no option, the select renders unselected, and on iOS that stops the user from picking the first option, because no change event fires for it. The Vue docs recommend a disabled placeholder option with an empty value for that reason.
Modifiers
v-model has three modifiers of its own:
<!-- sync on "change" (blur or Enter), not on every keystroke -->
<input v-model.lazy="title" />
<!-- convert to a number with parseFloat -->
<input v-model.number="quantity" />
<!-- strip leading and trailing whitespace -->
<input v-model.trim="email" />
.number exists because every input value is a string, even in a field that looks numeric, so quantity + 1 would concatenate. With .number, Vue runs the value through parseFloat; if that cannot produce a number, the original string is kept. On <input type="number">, Vue applies .number automatically. Modifiers can be combined, as in v-model.trim.lazy.
.lazy is useful when every keystroke would trigger something expensive, such as validation or a filter over a large list, and it is fine to update only when the user leaves the field.
A note on IME input
For languages typed through an input method editor, such as Chinese, Japanese or Korean, a character is composed over several keystrokes. v-model deliberately does not update during composition and writes the value once the character is committed. If you need every intermediate value, for a live character count say, use :value and @input yourself.
What the video covers
The embed is the last lesson of Adam Jahr’s Composition API version of Vue Mastery’s Intro to Vue 3, in <script setup>. It builds a product review form with v-model on a text input, a textarea and a select, uses v-model.number to keep the rating numeric, holds the fields in a reactive() object, and submits with @submit.prevent, which ties back to the previous lesson. Because it is the course finale, it also passes the finished review to a parent component with defineEmits, which belongs to component events and emits; that part can be skimmed for now. Checkboxes, radios, .lazy, .trim and the IME behaviour are not in the clip. Vue School’s checkbox chapter, linked below, fills the first gap on video.
Where this fits
v-model also works on your own components, where it becomes a prop plus an emitted event, and since Vue 3.4 defineModel() makes that a one-liner. That is v-model on components. Validation, error messages and form libraries come later in forms and validation in Vue, and the browser’s own form features are covered in forms and form validation. The next group, starting with ref and reactive, explains how the state behind all these bindings is tracked.
Check yourself
What does `<input v-model="name">` roughly expand to?
`<input :value="name" @input="name = $event.target.value">`. Vue binds the input's value to the state and writes the new value back to the state on every `input` event.
Three checkboxes all have `v-model="toppings"` with values `cheese`, `ham` and `olives`, and `toppings` starts as `['ham']`. What happens when the user ticks cheese?
The ham box starts checked, because its value is in the array. Ticking cheese adds `'cheese'` to the array, so `toppings` becomes `['ham', 'cheese']`. Unticking a box removes its value. Binding several checkboxes to one array collects the values of the checked ones.
An age field uses `<input type="text" v-model="age">`, and `age + 1` produces `"301"` when the user types 30. Why, and what fixes it?
Input values are always strings, so `age` holds `"30"` and `+ 1` concatenates. Adding `.number` (`v-model.number="age"`) makes Vue convert the value with `parseFloat`, so `age` becomes the number 30. Using `type="number"` would apply that conversion automatically.
Why does `<input v-model="query" value="shoes">` not start with "shoes" in the box?
`v-model` treats the bound state as the only source of truth and ignores the `value` attribute in the template. The input shows whatever `query` holds. To start with "shoes", initialise the state: `const query = ref('shoes')`.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.