๐ฃIf you're following my blog posts, you already know that for the past few weeks I am exploring Vue.js and along with it I am also documenting my journey. So, today's post is about the v-model
directive in Vue.js.
๐ 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.
๐ Say Hi
I am quite active on Twitter you can follow me there or visit my Blog to know more about me.
Top comments (2)
I'm learning Vue too, thank you for your post, I'm not already using forms but I will sooner or later and now I know this ๐
๐ Great, You'll surely enjoy learning Vue.
Let me know if I could help you with any thing.