Component v-model
Basic Usage
v-model can be used on a component to implement a two-way binding.
Starting in Vue 3.4, the recommended approach to achieve this is using the defineModel() macro:
```vue [Child.vue]
The parent can then bind a value with `v-model`:
```vue-html [Parent.vue]
<Child v-model="countModel" />
The value returned by defineModel() is a ref. It can be accessed and mutated like any other ref, except that it acts as a two-way binding between a parent value and a local one:
- Its
.valueis synced with the value bound by the parentv-model; - When it is mutated by the child, it causes the parent bound value to be updated as well.
This means you can also bind this ref to a native input element with v-model, making it straightforward to wrap native input elements while providing the same v-model usage:
<script setup>
const model = defineModel()
</script>
<template>
<input v-model="model" />
</template>
Under the Hood
defineModel is a convenience macro. The compiler expands it to the following:
- A prop named
modelValue, which the local ref's value is synced with; - An event named
update:modelValue, which is emitted when the local ref's value is mutated.
This is how you would implement the same child component shown above prior to 3.4:
```vue [Child.vue]
Then, `v-model="foo"` in the parent component will be compiled to:
```vue-html [Parent.vue]
<Child
:modelValue="foo"
@update:modelValue="$event => (foo = $event)"
/>
As you can see, it is quite a bit more verbose. However, it is helpful to understand what is happening under the hood.
Because defineModel declares a prop, you can therefore declare the underlying prop's options by passing it to defineModel:
// making the v-model required
const model = defineModel({ required: true })
// providing a default value
const model = defineModel({ default: 0 })
[!WARNING] If you have a
defaultvalue fordefineModelprop and you don't provide any value for this prop from the parent component, it can cause a de-synchronization between parent and child components. In the example below, the parent'smyRefis undefined, but the child'smodelis 1:```vue [Child.vue]
>
```vue [Parent.vue]
<script setup>
const myRef = ref()
</script>
<template>
<Child v-model="myRef"></Child>
</template>
Also, when using
withDefaultswithdefineProps, default values for mutable reference types (like arrays or objects) should be wrapped in functions indefineModelto avoid accidental modification and external side effects.
First let's revisit how v-model is used on a native element:
<input v-model="searchText" />
Under the hood, the template compiler expands v-model to the more verbose equivalent for us. So the above code does the same as the following:
<input
:value="searchText"
@input="searchText = $event.target.value"
/>
When used on a component, v-model instead expands to this:
<CustomInput
:model-value="searchText"
@update:model-value="newValue => searchText = newValue"
/>
For this to actually work though, the <CustomInput> component must do two things:
- Bind the
valueattribute of a native<input>element to themodelValueprop - When a native
inputevent is triggered, emit anupdate:modelValuecustom event with the new value
Here's that in action:
```vue [CustomInput.vue]
Now `v-model` should work perfectly with this component:
```vue-html
<CustomInput v-model="searchText" />
Another way of implementing v-model within this component is to use a writable computed property with both a getter and a setter. The get method should return the modelValue property and the set method should emit the corresponding event:
```vue [CustomInput.vue]
## `v-model` Arguments
`v-model` on a component can also accept an argument:
```vue-html
<MyComponent v-model:title="bookTitle" />
In the child component, we can support the corresponding argument by passing a string to defineModel() as its first argument:
```vue [MyComponent.vue]
[Try it in the Playground](https://play.vuejs.org/#eNqFklFPwjAUhf9K05dhgiyGNzJI1PCgCWqUx77McQeFrW3aOxxZ9t+9LTAXA/q2nnN6+t12Db83ZrSvgE944jIrDTIHWJmZULI02iJrmIWctSy3umQRRaPOWhweNX0pUHiyR3FP870UZkyoTCuH7FPr3VJiAWzqSwfR/rbUKyhYatdV6VugTktTQHQjVBIfeYiEFgikpwi0YizZ3M2aplfXtklMWvD6UKf+CfrUVPBuh+AspngSd718yH+hX7iS4xihjUZYQS4VLPwJgyiI/3FLZSrafzAeBqFG4jgxeuEqGTo6OZfr0dZpRVxNuFWeEa4swL4alEQm+IQFx3tpUeiv56ChrWB41rMNZLsL+tbVXhP8zYIDuyeQzkN6HyBWb88/XgJ3ZxJ95bH/MN/B6aLyjMfYQ6VWhN3LBdqn8FdJtV66eY2g3HkoD+qTbcgLTo/jX+ra6D+449E47BOq5e039mr+gA==)
If prop options are also needed, they should be passed after the model name:
```js
const title = defineModel('title', { required: true })
```vue [MyComponent.vue]
[Try it in the Playground](https://play.vuejs.org/#eNp9kE1rwzAMhv+KMIW00DXsGtKyMXYc7D7vEBplM8QfOHJoCfnvk+1QsjJ2svVKevRKk3h27jAGFJWoh7NXjmBACu4kjdLOeoIJPHYwQ+ethoJLi1vq7fpi+WfQ0JI+lCstcrkYQJqzNQMBKeoRjhG4LcYHbVvsofFfQUcCXhrteix20tRl9sIuOCBkvSHkCKD+fjxN04Ka57rkOOlrMwu7SlVHKdIrBZRcWpc3ntiLO7t/nKHFThl899YN248ikYpP9pj1V60o6sG1TMwDU/q/FZRxgeIPgK4uGcQLSZGlamz6sHKd1afUxOoGeeT298A9bHCMKxBfE3mTSNjl1vud5x8qNa76)
In this case, instead of the default `modelValue` prop and `update:modelValue` event, the child component should expect a `title` prop and emit an `update:title` event to update the parent value:
```vue [MyComponent.vue]
<script>
export default {
props: ['title'],
emits: ['update:title']
}
</script>
<template>
<input
type="text"
:value="title"
@input="$emit('update:title', $event.target.value)"
/>
</template>
Multiple v-model Bindings
By leveraging the ability to target a particular prop and event as we learned before with v-model arguments, we can now create multiple v-model bindings on a single component instance.
Each v-model will sync to a different prop, without the need for extra options in the component:
<UserName
v-model:first-name="first"
v-model:last-name="last"
/>
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>
<template>
<input type="text" v-model="firstName" />
<input type="text" v-model="lastName" />
</template>
