Vue JS 2 Events


Vuejs events something like when the user clicks on the button or hover on the button then react in js some performance. in this post, we learn different types of events in Vue js.

Click events in Vuejs

So right now we just write code in an HTML page.

index.html

   <div id="vue-app">
        <h3>Events</h3>
        <button v-on:click="age++">Add</button>
        <button v-on:click="age--">Subtract</button> <br>   
        {{age}}
    </div>

Here we print age which is defined in Vue instance and two different buttons add and subtract when we click on button events will be active and change the value of age. 

When we click on the add button the value of age will be increment.

When we click on the second button the value of age will be subtracted.

app.js

 new Vue({
    el: '#vue-app', 
   
   	data:{
          age:25,
   	},
 });

 

Another method(a best practice) to do this event is we can use the method function in Vue instance. so we can perform this same task using this code.

index.html

    <div id="vue-app">
        <h3>Events</h3>
        <button v-on:click="add">Add</button>
        <button v-on:click="subtract">Subtract</button> <br>   
        {{age}}
    </div>

app.js

 new Vue({
    el: '#vue-app', 
   
   	data:{
          age:25,
           },
        methods:{
                add:function () {
                        this.age++
                },
                subtract:function(){
                        this.age--
                }
        }
 });

 

Double click events in Vue js

Double click events are when we click on button twice time then events will be in action.

   <div id="vue-app">
        <h3>Events</h3>
        <button v-on:dblclick="add">Add</button>
        <button v-on:dblclick="subtract">Subtract</button> <br>   
        {{age}}
    </div>

 

Passing Parameter in click event in Vue js

In this part, we are passing a parameter to Vue Instance.

index.html

   <div id="vue-app">
        <h3>Events</h3>
        <button v-on:click="add(10)">Add</button>
        <button v-on:click="subtract(10)">Subtract</button> <br>   
        {{age}}
    </div>

Here we passing a parameter 10 to Vue instance and add or subtract the value of age.

app.js

 new Vue({
    el: '#vue-app', 
   
   	data:{
          age:25,
           },
        methods:{
                add:function (inc) {
                        this.age += inc
                },
                subtract:function(des){
                        this.age -=des
                }
        }
 });

 

So these are some example of click events in Vue js.