v-model on components
What v-model compiles to on a component, the modelValue prop and update event underneath, defineModel since Vue 3.4, multiple v-models, and modifiers.
v-model on components
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- On a component, `v-model="x"` is shorthand for a prop plus an event: `:modelValue="x"` and `@update:modelValue="v => x = v"`. It doesn't break one-way data flow; it packages it.
- `defineModel()`, stable since Vue 3.4, declares that prop and event for you and returns a ref. Reading it reads the prop; assigning to it emits `update:modelValue`.
- Arguments name the binding: `v-model:title` pairs with `defineModel('title')`. Several named v-models can sit on one component, each with its own prop and event.
- Custom modifiers such as `v-model.capitalize` reach the child as a modifiers object. Destructure it from `defineModel()` and use the `set` (or `get`) option to transform the value.
- If `defineModel` has a `default` and the parent passes nothing, the child shows the default while the parent's variable stays `undefined`. The two drift apart.
The problem: a form control as a component
v-model on native inputs keeps an <input> and a ref in sync with one directive. As soon as you wrap that input in your own component, say a styled SearchBox with a clear button, you want the same convenience:
<SearchBox v-model="query" />
But the last two lessons set a rule: a child can’t change its parent’s state. It can only receive props and emit events. Two-way binding looks like it breaks that rule. It doesn’t. v-model on a component is just a prop and an event with a naming convention.
What v-model compiles to
On a component, the template compiler expands v-model into this:
<SearchBox
:modelValue="query"
@update:modelValue="(newValue) => (query = newValue)"
/>
The value goes down as a prop called modelValue. Changes come back up as an event called update:modelValue, and the parent’s listener performs the assignment. Data still flows one way. v-model just saves you writing the pair.
Before Vue 3.4, the child wired this up by hand:
<!-- SearchBox.vue, the manual protocol -->
<script setup>
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<input
:value="modelValue"
@input="emit('update:modelValue', $event.target.value)"
/>
</template>
That works and you’ll see it in older codebases. Many components also wrapped it in a writable computed with a get that returned the prop and a set that emitted the event. It’s worth recognising, but it is no longer how you write new components.
defineModel: the protocol as one line
defineModel became stable in Vue 3.4. It declares the modelValue prop and the update:modelValue event for you and returns a ref that speaks the protocol:
<!-- SearchBox.vue -->
<script setup>
const model = defineModel()
</script>
<template>
<div class="search">
<input v-model="model" placeholder="Search…" />
<button @click="model = ''">Clear</button>
</div>
</template>
Reading model.value reads the parent’s prop. Assigning to it emits update:modelValue, the parent’s variable updates, and the new value flows back down. You can pass the ref straight to a native v-model, as above, or assign it anywhere in script or template.
defineModel accepts the same options as a prop:
const model = defineModel({ type: String, required: true })
const count = defineModel({ default: 0 })
With TypeScript, defineModel<string>() types the ref.
One subtle behaviour: if the parent doesn’t bind v-model at all, the ref still works as local state inside the child. That makes a component usable both controlled and uncontrolled, a distinction React makes explicit in controlled vs uncontrolled components.
The default-value trap
A default on defineModel has a catch, and the Vue docs call it out:
<!-- Child.vue -->
<script setup>
const model = defineModel({ default: 1 })
</script>
<!-- Parent.vue -->
<script setup>
const myRef = ref() // undefined
</script>
<template>
<Child v-model="myRef" />
</template>
The child falls back to 1, but nothing is emitted until the value changes, so the parent’s myRef stays undefined. Two components now disagree about the same value. Initialise state in the parent that owns it, or make the model required.
Named and multiple v-models
v-model takes an argument that names the binding. The argument becomes the prop name, and the event becomes update:<name>:
<!-- Parent -->
<UserName v-model:first-name="first" v-model:last-name="last" />
<!-- UserName.vue -->
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>
<template>
<input v-model="firstName" />
<input v-model="lastName" />
</template>
Each binding is independent, so one component can expose several two-way values. A date-range picker with v-model:start and v-model:end is a typical case.
Custom modifiers
Native v-model has .trim, .number, and .lazy. Components can define their own. The modifiers used on the binding arrive as an object, which you get by destructuring defineModel():
<!-- Parent -->
<MyInput v-model.capitalize="text" />
<!-- MyInput.vue -->
<script setup>
const [model, modifiers] = defineModel({
set(value) {
if (modifiers.capitalize) {
return value.charAt(0).toUpperCase() + value.slice(1)
}
return value
},
})
</script>
<template>
<input v-model="model" />
</template>
modifiers is { capitalize: true }. The set option transforms each value before it is emitted, and a matching get option transforms values on the way in. For a named model the pattern is the same: const [title, titleModifiers] = defineModel('title'). Under the hood the modifiers travel as a prop named modelModifiers, or titleModifiers for v-model:title.
What the video covers
Andre Madarang builds a child input component and binds it with v-model four ways: the manual modelValue prop and update:modelValue event, a writable computed, VueUse’s useVModel, and finally defineModel. Seeing the progression is the best way to understand that defineModel is sugar over a protocol, not new magic. The video was recorded on Vue 3.3, when defineModel was still experimental and needed an opt-in flag. It has been stable since 3.4 and needs no configuration. Named models, modifiers, and the default-value trap are covered above in prose. Program With Erik’s 3.4 overview shows stable defineModel with modifiers, and LearnVue’s short video looks at how the returned ref behaves when the parent doesn’t bind it.
Check yourself
What does `<SearchBox v-model="query" />` compile to, and why does that respect one-way data flow?
It becomes `<SearchBox :modelValue="query" @update:modelValue="(v) => (query = v)" />`. The child still receives the value as a read-only prop and asks for changes with an event; the parent's listener performs the assignment. `v-model` only saves writing the prop and listener by hand.
Inside a child using `const model = defineModel()`, what happens when the code runs `model.value = 'hi'`?
Nothing is mutated in the parent directly. The ref's setter emits `update:modelValue` with `'hi'`; the parent's v-model listener assigns it to its own variable; the new value then flows back down as the `modelValue` prop, and the child's ref reflects it.
How would a `UserForm` component support both `v-model:first-name` and `v-model:last-name`?
Declare one model per binding: `const firstName = defineModel('firstName')` and `const lastName = defineModel('lastName')`. Each creates its own prop (`firstName`, `lastName`) and event (`update:firstName`, `update:lastName`), and the parent can bind both on the same tag.
Why can `defineModel({ default: 1 })` cause the parent and child to disagree?
If the parent doesn't bind anything, the child falls back to its default and shows 1, but no event is emitted until the value changes, so the parent's variable stays `undefined`. The child and parent now hold different values for the same thing. Initialise the value in the parent, or mark the model `required`, to avoid it.
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.