v-model — Vue JS
Moving to Vue from React, it was a bit difficult for me to understand the Vue way of coding. I didn’t get much time to go too deep with all the new concepts due to the timeframe to finish the project during an internship, but as I study and write codes in Vue, I learned about v-model
that can be useful for writing codes efficiently. It was a little confusing (still is) to understand the concept, so this is to organize my thoughts about the concept ofv-model
.
When I want to listen to a change event of inputs and update a certain state to the value entered by a user, I would make a method that takes the event as a parameter and sets the state to the e.target.value
. I was doing the same with Vue JS project, but then I realized this isn’t quite a useful way although it works fine.
v-model
is basically a combination of two attributes, v-bind
and v-on
. It lets you to write in a simpler form instead of wiring v-bind:value
and v-on:input
each time. Depending on which tag to use v-model for, it has different types of attributes — for input tags, it has value
and input
, for select tags, value
and change
and for checkbox tags, checked
and change
.
<input v-model="searchText" />
According to the Vue official document, the above code will be the same with:
<input :value="searchText" @input="searchText = $event.target.value" />
In the above example, the value entered into the input by a user will be automatically updated to the searchText data.