How to handle the events in Vue
In this tutorial, we are going to learn about event handling in Vue.js with the help of examples.
Vue offers us a special directive called v:on which helps us to register and listen to the dom events, so that whenever an event is triggered the method passed to that event is invoked.
The syntax of the v:on directive.
<!-- v:on:eventname="methodname" -->
<button v:on:click="handleClick">Click</button>
In the above code, we are listening to the click
event on the button so that whenever a user is clicked on the button, it invoked the handleClick
method.
Counter example
<template>
<div>
<h1>{{num}}</h1>
<button v-on:click="increment">Increment</button> </div>
</template>
<script>
export default{
data:function(){
return{
num:0
}
},
methods:{
increment:function(){
this.num=this.num+1
}
}
}
</script>
Passing arguments to the Event handler
Sometimes, Event handler methods can also accept arguments let’s see an example.
<template>
<div>
<h1>{{num}}</h1>
<!-- argument 10 is passed to the `increment method -->
<button v-on:click="increment(10)">Increment By 10</button> </div>
</template>
<script>
export default{
data:function(){
return{
num:0
}
},
methods:{
//parameter `value`
increment:function(value){
this.num =this.num+value
}
}
}
</script>
Here we created an increment
method with one parameter value
so that we are passing 10
as an argument to the increment()
method.
Acessing default event object
To access the default event object in methods, we need to use a special $event
variable offered by the vue.
<template>
<!-- we are passing a $event variable -->
<input placeholder="name" v-on:onchange="handleChange($event)" /></template>
<script>
export default{
methods:{
handleChange:function($event){
console.log($event.target.value)
}
}
}
</script>
Accessing both
we can also access both the event
object and arguments
inside the event handler method like this.
<template>
<!-- we are passing argument plus $event variable -->
<button v-on:click="hitMe('You hitted me',$event)"> Hit me Hard </button></template>
<script>
export default{
methods:{
handleChange:function(message,$event){
$event.preventDefault()
console.log(message)
}
}
}
</script>
Shorthand syntax
There is also a shorthand syntax for listening to the dom events.
<!--short hand syntax @eventname="method" -->
<button @click="handleClick"></button>
<!-- long hand syntax -->
<button v-on:click="handleClick"></button>