Anthony

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 (){
    return{
      anything: ''
    }
  }

Checkboxes

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

Set a value

    data (){
    return{
      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 (){
    return{
      picked: ''
    }
  }

Select

<select v-model="selected">
      <option disabled value="">Choose a System</option>
      <option>Mac</option>
      <option>Windows</option>
      <option>Linux</option>
</select>
<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">
</form>

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 (){
    return{
      address: '',
      fullname: '',
      recipt: false,
      shippingType: ''
    }
  },
    methods:{
    startShipping(){
      console.log(this.address);
      console.log(this.fullname);
      console.log(this.recipt);
      console.log(this.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