Search⌘ K
AI Features

The V-Model Directive and Two-Way Data Binding

Explore how to implement two-way data binding using the v-model directive in Vue 3. Understand the migration changes from Vue 2 to Vue 3, including the deprecation of the .sync modifier and model option. Learn to use multiple v-models on single components and update custom components to use the modelValue prop and update:modelValue event for improved reactivity.

Two-way data binding using v-model

Two-way data binding on a form element or component can be achieved using the v-model directive. Below is a simple example of using this directive.

Vue 2

HTML
<my-component :value="title" @input="title = $event" />
<!-- Next line is a short version of the above line so we can use either one of two lines. -->
<my-component v-model="title" />

Let’s look at the script for the my-component component:

Javascript (babel-node)
// MyComponent.vue
export default {
props: {
value: String
}
}

The v-model directive is over the value prop and input event, syntactically speaking. These can be renamed by using the model option:

The model option

HTML
<my-component v-model="checkboxValue" />

Let’s look at the updated script for the my-component component:

Javascript (babel-node)
// MyComponent.vue
export default {
model: {
prop: 'checked',
event: 'update'
},
props: {
checked: {
type: Boolean,
default: false
}
},
methods: {
updateCheckboxValue(checked) {
this.$emit('update', checked)
}
}
}

In Vue 2, only one v-model can be specified on a component.

Vue 2 - sync modifier

Two-way data binding for multiple props could be achieved using the .sync modifier:

HTML
<my-component :text="form.message" @update:text="form.message = $event"/>
<!-- Next line is a short version of the above line so we can use either one of two lines. -->
<my-component :text.sync="form.message" />

Now look at the script for the my-component component:

Javascript (babel-node)
// MyComponent.vue
export default {
props: {
text: String
},
methods: {
update() {
this.$emit('update:text', 'new message')
}
}
}

Vue 3

The v-model directive was reworked in the new version of Vue. It can now be used multiple times on the same component. Because of this change, the .sync modifier and the model option were deprecated, as they’re no longer ...