VueJS Event Handling

📆 Last updated Jan 05, 2020 👷 By, Chandan Tudu

In this tutorial, you will learn how to handle DOM Events using VueJS. We can handle the DOM Events using the VueJS v-on: directive.

The v-on: directive is used to listen to DOM events and run some JavaScript when they are triggered.


Example

<div id="myApp">
  <button v-on:click="showAlert">Click Me</button>
<!--
      v-on: - Directive
      click - Event Name
  showAlert - Method
-->
</div>
var myApp = new Vue({
  el:'#myApp',
  methods:{
    showAlert:function() {
      alert("Welcome to VueJS.");
    }
  }
});

On Click Increment & Decrement Example

<div id="myApp">
  <h1>Number: {{number}}</h1>
  <button v-on:click="number++">Increment</button>
  <button v-on:click="number--">Decrement</button>
</div>
var myApp = new Vue({
  el:'#myApp',
  data:{
    number:0
  }
});

How to pass arguments or parameters in a method?

<div id="myApp">
  <h1>Number: {{number}}</h1>
  <button v-on:click="increment(10)">Increment</button>
  <button v-on:click="decrement(10)">Decrement</button>
</div>
var myApp = new Vue({
  el:'#myApp',
  data:{
    number:0
  },
  methods:{
    increment:function(add){
      this.number += add;
    },
    decrement:function(dec){
      this.number -= dec;
    }
  }
});

How to access the original event object?

If you want to access the original DOM event in an expression handler, you need to pass event object in as $event.

<div id="myApp">
  <button v-on:click="myClickEvent('Check the console log', $event)">Click Me</button>
</div>
var myApp = new Vue({
  el:'#myApp',
  methods:{
    myClickEvent:function(msg, event){
      console.log(event);
      alert(msg);
    }
  }
});

Shorthand of the v-on: directive

The Shorthand of the v-on: Directive is @

<div id="myApp">
  <!-- <button v-on:click="clickMe">Click Me</button> -->
  <button @click="clickMe">Click Me</button>
</div>
var myApp = new Vue({
  el:'#myApp',
  methods:{
    clickMe:function(){
      alert('Hello from Vue.JS!');
    }
  }
});

Leave a Reply

Your email address will not be published. Required fields are marked *