Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

VueJS Events

Most applications are event driven. An event is an action that happens like when a user clicks on a button, moves the mouse over something, double clicks on the page etc. Vue allows us to create listeners on various elements so that when the specified action happens, we do something about it.

In this lesson, we will learn how to work with events in Vue JS.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - this is mainly needed for development purposes only. You need NPM which comes with Node to work with tools like Vue CLI
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.
  • HTML & CSS Basics - this is an added advantage. Vue works on the HTML elements to manipulate them. The styling is done using CSS so you must be familiar with the basics

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called vue-components

Open the directory vue-components in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this is the file that will contain our application source code

The following visualizes our project setup

vue-components
-index.html

How to Create an Event Listener

Vue uses the v-on directive to attach events to elements. For example, you can create a button then use the v-on directive to make it call a function when you click on it. You can also use a JavaScript expression as the event handler.

Let's look at a simple event that keeps track of the number of times that a button is clicked.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Events</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <button v-on:click="counter++">{{counter}}</button>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    counter: 0
                }
            });
        </script>
    </body>
</html>

HERE,

  • data: {...} defines a data member counter that is initialized to 0.
  • <button v-on:click="counter++">{{counter}}</button> defines a button that has a click event as specified by the directive v-on. The event handler is a JavaScript expression counter++ that simply increments the value of the variable counter by 1.

Open the file index.html in the web browser

You should be able to see the following button

{{image place holder}}

Click on the button. You should be able to see the number on the button increase.

The v-on: directive has a shortcut @ which is easier to type compared to v-on. We can modify our above code as follows and it should still work

<button @click="counter++">{{counter}}</button>

Event Handlers

Let's now refactor our simple example and assign the click event to a method (the event handler). Modify the code with the body tag as follows.

<div id="root">
    <button @click="incrementCounter">{{counter}}</button>
</div>
<script type="text/javascript">
    let vm  = new Vue({
        el: '#root',
        data: {
            counter: 0
        },
        methods: {
            incrementCounter: function(){
                this.counter++;
            }
        }
    });
</script>

HERE,

  • <button @click="incrementCounter">{{counter}}</button> uses the shorthand @ to define a click event on our button. The event is attached to a function incrementCounter. Note we don't have to use the parenthesis like we do when calling normal functions.
  • methods: {...} defines a function incrementCounter: function(){...} that is called whenever the user clicks on the button. The function just increments the value of counter by 1.

Executing the above code should give us the same results as before.

Event Object

When working with events, we have an event object which is implicitly passed to the event handler when the event if fired. In the following example, we will create an event handler that displays the event object to the console and examine some of the information that is passed to the event

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Event Object</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <button v-on:click="eventObject">Log event object</button>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                methods: {
                    eventObject: function(event){
                        console.log(event);
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • <button v-on:click="eventObject">Log event object</button> calls attached the click event to the button with eventObject as the event handler
  • eventObject: function(event){...} we have a function that accepts a parament event. We are not explicitly passing in the argument for this parameter when calling the event handler. Vue handles this for us. console.log(event); prints the value of event to the terminal.

Open the file object.html in the web browser and open the dev tools console

Click on the button

You should be able to see the following result.

{{ image place holder }}

The event object is usually useful when you want to get some information from the element that the object is attached to. For example, if you have an input box where you enter something and you would like to make that data available in Vue without two way data binding, you can capture the value using the event object like so.

eventHandler: function(event){
    this.value = event.target.value;
}

HERE,

  • event.target refers to the element that fired the event, .value is the attribute of the calling element who value we want to access.

We will learn how to use the event object to get the target value on the section on Key Modifies below

Event Inline Methods

In the above example, we simply attached the method to the click event. In this section, we will learn how to inline methods within events and call them like normal functions. We will create a simple program that returns the square of a number that we pass in.

Open the file inline.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Inline</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <button v-on:click="printSquare(1)">Print square of 1</button>
            <button v-on:click="printSquare(2)">Print square of 2</button>
            <button v-on:click="printSquare(3)">Print square of 3</button>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                methods: {
                    printSquare: function(value){
                        console.log(value * value);
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • <button v-on:click="printSquare(1)">Print square of 1</button> calls the inline function printSquare(1) with the argument 1.
  • <button v-on:click="printSquare(2)">Print square of 2</button> calls the inline function printSquare(2) with the argument 2.
  • <button v-on:click="printSquare(3)">Print square of 3</button> calls the inline function printSquare(3) with the argument 3.
  • printSquare: function(value){...} defines a function that accepts a parameter and multiplies it by itself.

Open the file inline.html in the browser and open the developer tools console

Clicking on the buttons, You should be able to see the value of the respective number displayed in the terminal.

Event Modifiers

Event modifiers allow us to provide additional functionality for our events without writing the business logic for it in the event handlers. For example, you may want to allow the user to click a button once only. You can easily do this in the method but Vue provides a more generic way of doing this. You can use the event modify once directly on the event and let your methods be purely about business logic.

The following code shows how to use an event modifier

<button v-on:click.once="buttonClicked">{{count}}</button>

HERE,

  • v-on:click.once attaches the modifier once to the event click. The once modifier is used to execute the event once only. There after, the event is not fired when the user clicks on the event.

Multiple event modifiers can be chained together like so

<button v-on:click.prevent.once="buttonClicked">{{count}}</button>

Multiple modifies are chained together using the dot notation @click.prevent.once

Event Key Modifiers

Key modifiers allow us to listen to keyboard events. For example, you can have an input box where the user enters something then presses the enter key. After pressing the enter key, you may want to process the input entered by the user.

The following example allows the user to enter a numeric value in USD then we convert it to Tanzanian Shillings when the user presses enter key.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Events Key Modifiers</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Enter amount in USD then press Enter key</p>
            <input v-on:keyup.enter="displayRate">
            <p>Amount in TZS is {{amount_in_local}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    amount_in_local : 0
                },
                methods: {
                    displayRate: function(event){
                        this.amount_in_local = event.target.value * 2390;
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • <input v-on:keyup.enter="displayRate"> uses the key modifier enter on the event keyup. The event handler is displayRate
  • displayRate: function(event){...} defines a function for our event. this.amount_in_local = event.target.value * 2390; gets the value that was entered in the input box from the event object and we use it to work with the exchange rate of 2390. The result is then assigned to the data member amount_in_local
  • <p>Amount in TZS is {{amount_in_local}}</p> displays the value of amount_in_local in the browser.

Open the file key.html in the web browser

You should be able to get the following results after entering a value and pressing the enter key.

{{image place holder}}

Summary

Events refers to specific actions that happen like clicking a button, typing on the keyboard etc. These events are associated with event handler which specify the action to be taken when an event occurs. Vue use v-on: directive to attach an event to an element. You can also use @event as a shorthand of using v-on. The event object contains information about the event and gives us access to data from the calling element.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

VueJS Data Binding

VueJS Filters

Leave A Reply