Understanding the v-model Directive in Vue.js

Understanding the v-model Directive in Vue.js

The v-model directive allows us to create a two-way data bindings on form input, textarea, and select elements.

A basic example:

<input v-model="anything" type="text" placeholder="Type anything...">
<p>Something is {{ anything }} </p>

To make it work you have to define it on the instance:

    data (){
      anything: ''


    <input type="checkbox" value="foo" v-model="checked">

Set a value

    data (){
      checked: false

Radio Buttons

<input type="radio"  value="one" v-model="picked">
<input type="radio"  value="two" v-model="picked">
<p>You  picked: {{picked}} </p>

Set picked to a empty string:

    data (){
      picked: ''


<select v-model="selected">
      <option disabled value="">Choose a System</option>
<p>System chosen: {{ selected }}</p>

From the examples above we can certainly say that the v-model directive does all the tedious works for us. Which makes it easy to work with inputs and data from inputs. Bring all together let’s try something that we’re most likely to use in real life.

Let’s use an uncomplete shipping form for the example

      <h1>Shipping Details</h1>
<form @submit.prevent="startShipping">
    <input v-model="fullname" type="text" placeholder="Enter Fullname...">
    <input v-model="address" type="text" placeholder="Address">
    <label for="recipt">Don't include recipt</label>
    <input type="checkbox" v-model="recipt">
        <span>Select shipping type</span>
        <label>Free shipping 2 weeks</label>
        <input type="radio"  value="free shipping 2 weeks" v-model="shippingType">
      <label>Paid shipping 2 days: $10</label>
     <input type="radio"  value="paid shipping 2 days" v-model="shippingType">
      <input type="submit" value="Start Order">

Without doubt, we know very well that we have full access to the data coming from the inputs, we can choose to do anything with the data or just simply log them to the console.

 data (){
      address: '',
      fullname: '',
      recipt: false,
      shippingType: ''

Try messing around with the v-model directive, manipulate the data on your own and see how fast you graps it. I hope you find this article helpful.

comments powered by Disqus