My Journey

Two-way binding in Vue.js

February 07, 2020

πŸ‘‰ For the two-way binding, Vue provides v-model directive, let’s explore it in depth:

♻️ v-model:

The v-model directive helps us create a two-way binding on form inputs <input>, textarea <textarea>, and select elements <select>.

Binding to <input> element:

Let’s suppose we have a data property named data and we can bind it with v-model on the input element like this

<input v-model="book" placeholder="What's your favorite book?">
<p>Your Favorite book is: {{ book }} </p>

Binding to <textarea> element:

Binding message data property with v-model

<textarea v-model="message" placeholder="Share your message"></textarea>
<p>Message: {{ message }}</p>

Binding to <select> element:

Binding selected data property with v-model

select v-model="selected">
  <option disabled value="">Please select one</option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
<span>Selected: {{ selected }}</span>

Vue also provides some modifiers for the v-model directive that sometimes makes life easier πŸ˜…

Modifiers

.lazy
By default v-model sync the input with the data after each input event but by using v-model.lazy we can restrict it to only after the change event.

.trim
This modifier is used when we want to trim whitespace from user input.

.number
When we want to automatically typecast user input as a number we use v-model.number and it trims the whitespace.

P.S: Your feedback helps me improve myself and motivates me to share more content.


Zahid Jabbar

πŸ“ Thoughts by Zahid Jabbar.
Who aspires to be a full-stack developer.