The V-Model Directive and Two-Way Data Binding
Learn how two-way data binding is achieved in Vue 2 and Vue 3 using the v-model directive.
We'll cover the following...
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
<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:
// MyComponent.vueexport 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
<my-component v-model="checkboxValue" />
Let’s look at the updated script for the my-component
component:
// MyComponent.vueexport 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:
<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:
// MyComponent.vueexport 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 ...