In the Event Handling lesson, the text typed into an input was read with @input="customer = $event.target.value". That works, but it's long, and it only goes one way: from the input to the data. If the script empties customer, the input still shows the old text.
v-model is a directive that ties a form field (an input, a select or a textarea) to reactive data, in both directions. Typing changes the data, and changing the data changes what's in the field. This is called two-way binding. Picture a small whiteboard on the counter at Mrs. Sri's stall that two people share. The customer writes their order on the board, and Mrs. Sri reads it from the same board. If Mrs. Sri erases "spicy" because there are no chillies left, the customer sees it disappear right away. In Vue, the board is a ref. The customer who writes is the user typing in the field, and Mrs. Sri who erases is your code changing the ref. v-model makes the field and your code use the same board.
v-model: the field and the data become one
Here is a customer name field tied to the ref name with v-model:
const name = ref("")
---template---
<input v-model="name" placeholder="Customer name" />
<p>Order for: {{ name }}</p>
<button @click="name = ''">Clear</button>
| Event | name |
In the field | Paragraph |
|---|---|---|---|
| Page appears | "" |
empty | Order for: |
| Type "Sri" | "Sri" |
Sri | Order for: Sri |
| Click Clear | "" |
empty | Order for: |
- First direction: every keystroke is written to
nameright away, with no button at all. - Second direction:
name = ''on the Clear button empties the data, and the field empties with it. - The typed text is kept in the data, not only in the input element. So if an input with
v-modelsits inside av-ifblock, the input is removed when the condition is false, but its text comes back when the block appears again. - For a text field,
v-model="name"is roughly:value="name"plus@input="name = $event.target.value"from the Event Handling lesson. For checkboxes and radios,v-modelusescheckedand thechangeevent. For a select,v-modeluses thechangeevent.v-modelhandles all of it. - In the first exercise, you write
<input id="name" v-model="name" />and<p id="preview">{{ name }}</p>. TypeSinta, and the paragraph readsSintaright away. - The field's starting value comes from its ref. The
valueattribute is ignored. For example,<input v-model="name" value="Budi" />withnameholding""shows empty. - What goes in
v-modelmust be something that can be given a new value: a ref's name, or a property likecart.note.v-model="name.toUpperCase()"fails to compile. In development mode, the console writes[Vue warn]: Template compilation error: v-model value must be a valid JavaScript member expression., and the Playground only showshttps://vuejs.org/error-reference/#compiler-42. v-modelalso works on a component you write yourself, for example<PortionCount v-model="rice" />. How to do it, withdefineModel(), is in the Emits lesson, after you know props and component events.
Checkbox, radio, select and textarea
Here is v-model on checkboxes, radios, a select and a textarea:
const takeaway = ref(false)
const extras = ref([])
const spice = ref("Medium")
const menu = ref("Chicken Noodles")
const note = ref("")
---template---
<label><input type="checkbox" v-model="takeaway" /> Takeaway</label>
<label><input type="checkbox" value="Egg" v-model="extras" /> Egg</label>
<label><input type="checkbox" value="Crackers" v-model="extras" /> Crackers</label>
<label><input type="radio" value="Not spicy" v-model="spice" /> Not spicy</label>
<label><input type="radio" value="Medium" v-model="spice" /> Medium</label>
<label><input type="radio" value="Hot" v-model="spice" /> Hot</label>
<select v-model="menu">
<option>Fried Rice</option>
<option>Chicken Noodles</option>
<option>Iced Tea</option>
</select>
<textarea v-model="note"></textarea>
| Element | What the data holds | Example |
|---|---|---|
| One checkbox | true or false |
tick Takeaway: takeaway becomes true |
| Several checkboxes, one array | an array of the ticked values |
tick Crackers then Egg: ["Crackers", "Egg"] |
| Radio | the chosen value |
pick Hot: "Hot" |
| Select | the chosen option's value, or its text when it has no value |
Chicken Noodles is selected from the start |
| Textarea | its text | "no vegetables" |
- The ref's starting value decides which option is selected. In the second exercise, you write
const color = ref("Red"),<select id="color" v-model="color">with the options Red, Green, Blue, then<p id="choice">{{ color }}</p>. When the page appears, the paragraph readsRed. Pick Green, and it readsGreen. Pick Blue, and it readsBlue. - Several checkboxes for one piece of data must start from an array,
ref([]). The order of the array's items follows the order they were ticked. - A textarea's content is tied through
v-model, not with{{ }}between its tags.
.number, .trim, .lazy
These two fields record numbers of portions, and the paragraph adds them up:
const rice = ref(0)
const tea = ref(0)
---template---
<input v-model="rice" /> portions of Fried Rice
<input v-model="tea" /> glasses of Iced Tea
<p>Total portions: {{ rice + tea }}</p>
| Written | rice after you type 1 |
Total, after you type 1 and 2 |
|---|---|---|
v-model="rice" |
"1", text |
12 |
v-model.number="rice" |
1, a number |
3 |
Without .number, the total is 12, not 3. A field's content is always text, so "1" + "2" joins text instead of adding numbers. With .number on both fields, the total is 3. Multiplication still gives the right result by chance ("1" * 15 gives 15), which is why this bug often goes unnoticed.
Like events, v-model also has modifiers (endings with a dot):
| Modifier | What it does | Example |
|---|---|---|
.number |
turns the field's content into a number | "2 portions" becomes 2; "two" stays the text "two" because it can't become a number |
.trim |
removes spaces at the start and end | " Sri " becomes "Sri" |
.lazy |
only writes to the data on the change event, that is, when you move out of the field or press Enter |
typing "Sri" doesn't change name yet |
- In Vue 3, the content of
<input type="number" v-model="rice" />becomes a number by itself. Careful: a number field that's emptied holds the text"". - Modifiers can be chained:
v-model.trim.lazy="name".
⚠️ Numbers that turn out to be text, and boxes that all tick at the same time
- Numbers that are really text.
{{ rice + tea }}gives12, not3. Usev-model.numberortype="number". .lazyfor a live preview. With.lazy, the paragraph only changes after you move out of the field. In the first exercise, the checker typesSintaand reads#previewright away, so use plainv-model.- A checkbox group without an array. If
extrasstarts asref(""), ticking one box makesextrastrue, and every box in the group gets ticked with it. valueorselectedin the HTML.v-modelignores them. The starting value goes in the ref:ref("Red").
TL;DR: v-model="name" ties a form field (an input, a select, a textarea) and a ref in both directions: typing changes the data, and changing the data changes what's in the field. Text fields and textareas hold text. One checkbox holds true or false, and several checkboxes with ref([]) hold an array of the ticked values. Radios and selects hold the chosen value, and the ref's starting value decides what's selected. A field's content is always text. The modifier .number turns it into a number, .trim removes spaces at the start and end, and .lazy waits for the change event (when you move out of the field). The value attribute is ignored, and what goes in v-model must be a ref or a property that can be given a new value.
⚡ v-model: the field and the data become one
Write:
const name = ref("")
---template---
<input v-model="name" placeholder="Customer name" />
<p>Order for: {{ name }}</p>
<button @click="name = ''">Clear</button>
Guess first: v-model ties the field to the ref name. You type "Sri", then click Clear, which runs name = ''. Does the field empty too?
It does. name = '' empties the data, and the field empties with it, because v-model binds both ways.
Meaning: v-model is a directive that ties a form field (an input, a select or a textarea) to reactive data. First direction: every keystroke is written to name right away. Second direction: when the data changes, the field changes too. This is called two-way binding.
⚡ A select follows its ref
Write:
const menu = ref("Chicken Noodles")
---template---
<select v-model="menu">
<option>Fried Rice</option>
<option>Chicken Noodles</option>
<option>Iced Tea</option>
</select>
Meaning: The ref's starting value decides which option is selected, so Chicken Noodles is selected from the start. A value or selected attribute in the HTML is ignored by v-model.
⚡ A field always holds text
Write:
<input v-model="rice" /> portions of Fried Rice
<input v-model="tea" /> glasses of Iced Tea
<p>Total portions: {{ rice + tea }}</p>
Guess first: you type 1 in the rice field and 2 in the tea field. What's the total?
12, not 3. A field's content is always text, so "1" + "2" joins text.
Meaning: The modifier .number (an ending with a dot) turns the field's content into a number. With v-model.number="rice" and v-model.number="tea", the total becomes 3.