The v-model directive is the magic behind Vue's form handling.
It creates a two-way data binding between form input elements and your component's data state.
This means if the user types in the input, the data variable updates. If the data variable updates via code, the input field updates visually!
Behind the scenes, v-model is essentially syntax sugar.
It automatically combines binding the value attribute and listening to the input event.
You simply attach v-model="variableName" to any input, textarea, or select dropdown.
<input v-model="message" placeholder="Type here">
<p>You typed: {{ message }}</p>
The v-model directive perfectly handles complex inputs like checkboxes and radio buttons.
For a single checkbox, v-model binds to a boolean value (true or false).
If you have multiple checkboxes bound to the same array, it automatically populates the array with the checked values!
<input type="checkbox" v-model="isChecked"> <label>Accept Terms</label>
Vue provides three built-in modifiers for v-model to handle common edge cases:
.lazy: By default, v-model syncs on every keystroke. .lazy makes it sync only after the user clicks away (on the change event)..number: Automatically typecasts the user's input string into a true JavaScript Number..trim: Automatically strips any extra whitespace from the beginning and end of the input.<!-- Automatically convert input to a number --> <input v-model.number="age" type="number">
What does "two-way data binding" mean in the context of v-model?
Which modifier is used to ensure user input does not have accidental trailing spaces?