by Sai gowtham

Two-way data binding in Vue.js using v-model

In this tutorial we are going to learn about two-way data binding in vue by using v-model directive.

What is V-model directive ?

v-model directive helps us to create two-way data binding on the form elements (like input, textarea and select).

Let’s see an example.

<template>
 <input v-model="name" placeholder="name"/>  <p>{{name}}</p>
</template>

<script>
  export default{
      data:function(){
          return{
              name:""          }
      }
  }
</script>

Here we bind the form input element to the name property using v-model, so that when a user updates the input field it also updates the name property linked to it.

v-model-example-vuejs

Modifiers

v-model directive comes with a modifier options.

.lazy: By default v-model directive updates the data property on every keypress by adding .lazy modifier it only updates the data after a change event is triggered.

<template>
 <input v-model.lazy="name" placeholder="name"/>
</template>

.trim: It is used to remove the leading and trailing white spaces.

<template>
 <input v-model.trim="name" placeholder="name"/>
</template>

.number: If you want to accept number to the input field then you need to use .number modifier.

<template>
 <input v-model.number="age" placeholder="age"/>
</template>

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course