What is two-way data binding?
Two-way data binding is a mechanism where the data in the model and the display in the interface automatically stay in sync with each other.
In other words:
If the user changes a value in the UI -> the data in the component changes. If the data in the component changes -> the UI updates automatically.
In Vue this mechanism is implemented through the v-model directive.
A simple example
<input v-model="name">
<p>{{ name }}</p>If the user types text:
name = "Alex"
If you change the variable in code:
this.name = "John"- the value in the input updates too.
This is two-way binding.
How it works under the hood
Vue turns:
<input v-model="name">into two mechanisms:
- One-way binding (model -> view):
:value="name"- Reverse binding (view -> model):
@input="name = $event.target.value"Vue automatically combines this into convenient syntax.
What does two-way binding give you?
Saves code
You don't have to write input, change, keyup handlers by hand.
Simplifies forms
Especially multi-field ones, like validations.
A synchronized UI
The UI always shows the current data.
Two-way binding in components (Vue 3)
<MyInput v-model="value" />It works through:
- a prop:
modelValue - an event:
update:modelValue
The component:
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue']
}
</script>
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>Difference from one-way binding
| Binding type | What it does |
|---|---|
| one-way | Updates only the UI when the data changes |
| two-way | The UI and the data update each other |
Example of one-way:
<input :value="name">The UI cannot be used to change the model.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.