What is v-model used for?
v-model is a Vue directive for two-way data binding.
It links a value in the template (input, select, textarea, component) to a variable in the state, so that updating the value in the DOM changes the data, and updating the data changes the DOM.
In simple terms:
v-modelautomatically synchronizes the data and the interface.
How v-model works (using an input as an example)
<input v-model="name">This is syntactic sugar for:
<input
:value="name"
@input="name = $event.target.value"
/>In other words, Vue does v-bind + v-on itself.
Support for different form elements
Text inputs
<input v-model="text">Checkbox
<input type="checkbox" v-model="checked">Radio buttons
<input type="radio" value="A" v-model="choice">
<input type="radio" value="B" v-model="choice">Select
<select v-model="selected">
<option value="1">One</option>
</select>Checkboxes with arrays
<input type="checkbox" value="A" v-model="selectedItems">If the checkbox is checked, value is added to the array.
If it's unchecked, the value is removed.
v-model modifiers
.trim
Automatically trims whitespace at the edges
<input v-model.trim="name">.number
Converts the value to a number
<input v-model.number="age">.lazy
Fires on change, not on input
<input v-model.lazy="value">v-model in components (a very important topic)
In Vue 3:
<MyInput v-model="username" />Vue interprets this as:
- passing the
modelValueprop - listening for the
update:modelValueevent
Component example:
<script>
export default {
props: {
modelValue: String
},
emits: ['update:modelValue']
}
</script>
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
>
</template>Named models (Vue 3)
A component can have several v-models:
<DatePicker v-model:start="startDate" v-model:end="endDate" />The component must work with modelValue replaced by the argument:
- prop:
start - event:
update:start
How v-model works "under the hood"
Every v-model turns into a combination of:
v-bindto pass the valuev-onto update the data
So in effect it is:
:prop="value"
@event="value = $event"Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.