Vue v-model Directive

Vue v-model Directive

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!


How v-model Works

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.

Basic v-model Example:

<input v-model="message" placeholder="Type here">
<p>You typed: {{ message }}</p>

Checkboxes and Radio Buttons

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!

Checkbox Example:

<input type="checkbox" v-model="isChecked">
<label>Accept Terms</label>

v-model Modifiers

Vue provides three built-in modifiers for v-model to handle common edge cases:

Modifier Example:

<!-- Automatically convert input to a number -->
<input v-model.number="age" type="number">

Exercise 1 of 2

?

What does "two-way data binding" mean in the context of v-model?

Exercise 2 of 2

?

Which modifier is used to ensure user input does not have accidental trailing spaces?