Event Handling in VueJS

Event Handling is an important aspect of any javascript application. Let’s learn how we can handle user events in VueJS.

Problem: You want to capture user events (such as mouse clicks, or keyboard keypress) and perform some action based on the event.

Solution: We’ll build a simple VueJS Application which has two buttons for increasing and decreasing the counter.

    var app = new Vue({
        el: '#app',
        data: {
            count: 0
        }
    });

We have initiated a Vue instance that binds to the element with an id app and we have instantiated a single data property named count.

   <div id="app">
         <h2>{{count}}</h2>
         <button v-on:click="count += 1">Increase</button>
         <button v-on:click="count -= 1">Decrease</button>
    </div>

We have displayed the counter inside the h2 tag using mustache brackets and we have used two buttons, one for increasing the count and another for decreasing the count.

Notice the new directive v-on following the event which we are looking to capture in this case it’s click, and inside the quotes, we have written the logic of what needs to happen when the user clicks on the button, In one case we have increased the counter and in other, we have decreased it.

Demo

{{count}}

In this example, we have written the event handling logic inside the element itself, which would not be feasible for handling large and complex logics, next up we’ll see VueJS methods and how we can invoke methods on a user event.

tgugnani: Web Stuff Enthusiast.