WTF is Two-Way Binding in VueJS?
In Vuejs, you can use the v-model
directive to create two-way data bindings on form input, text-area and select elements. Two-way binding allows you to update the element based on the input type automatically. v-model
is essentially syntactical sugar for updating data on user input events.
<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
The property is set between the quotation marks. The property is the name we want to bind in both directions.
How is this different from v-bind
?
Remember v-model
is syntactical sugar.
<input v-model="something">
is syntactic sugar for:
<input
v-bind:value="something"
v-on:input="something = $event.target.value"
>
or shorthand syntax:
<input
:value="something"
@input="something = $event.target.value"
>
In summary: v-model
is a two-way binding for form inputs. It combines v-bind
which brings a js value into the markup, and v-on:input
to update the js value.
v-model
works with all basic HTML input types. Use it when you can, and use v-bind
/ v-on
when you must.