A Guide to Event Handling in Vue JS

In this post, you will be introduced to the way events are handled in Vue JS.

Lotanna Nwose
Bits and Pieces

--

Photo by MD Duran on Unsplash

Vue

Vue JS is a very progressive JavaScript framework created by Evan you and the Vue core team plus contributions from over 230 open source community lovers. Vue is used by more than 870,000 people and has been starred 140,000 times on GitHub. It consists of an approachable core library that focuses on the view layer only, and an ecosystem of supporting libraries that helps you tackle complexity in large Single-Page Applications.

In this post, you will be introduced to the way events are handled in Vue JS.

Tip: Use Bit (Github) to create, share and reuse your Vue components, across your projects and between your team and/or open-source community.

Bit’s Loaders Collection

Before you start

This post is suited for all stages of developers that use Vue JS, and this includes beginners. Here are a few prerequisites you should already have before going through this article.

You will need the following:

  • Node.js version 10.x and above installed. You can verify if you do by running the command below in your terminal/command prompt:
node -v
  • The Node Package Manager 6.7 or above (NPM) also installed.
  • A code editor: Visual Studio Code is highly recommended. (here’s why)
  • Vue’s latest version, installed globally on your machine.
  • Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:
npm uninstall -g vue-cli

then install the new one:

npm install -g @vue/cli
  • Download a Vue starter project here
  • Unzip the downloaded project
  • Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:
npm install

HTML Events

HTML events are simply events that happen to HTML elements, as the markup language is used primarily for presentation, it is then the work of JavaScript to add reactivity to these elements. It can be something the user does like a mouse click or hover or even something that a browser does like changing the DOM content or page load.

The syntax usually looks like this:

<element event=some JavaScript>

Some examples of these events are:

  • on change
  • on click
  • on mouse-over
  • on hover
  • on mouse-out
  • on key-down
  • on load

You can view the full JavaScript reference HTML DOM events list at the link here.

Handling events in Vue JS

To handle errors in Vue JS, the Vue team provides a directive called v-on, this directive listens to the DOM events and run some JavaScript when they are triggered. A simple on click example can be this:

<div id="example-1"> <button v-on:click="counter += 1">Add 1</button> <p>The button above has been clicked {{ counter }} times.</p></div>

This will listen to the button and when it is clicked, it adds one to the counter variable. Sometimes however, the logic you want to execute on the selected DOM element might be long enough to cross a line of code. It is better and more clean to represent it in a method instead. Vue JS supports this out of the box like every other framework. Now you will illustrate this with a simple Vue JS demonstration.

Demo: what you will be building

You will be building a simple Vue money counting application that has buttons. These buttons cause the value of money to increase on click. If you have followed this article from the beginning, you will have the Vue canvas project on your computer, open it in VS Code. Open the components folder inside the src directory and find the Test.vue file, it should look like this:

<template><div></div></template><script>export default {name: ‘Test’,props: {msg: String}}</script><! — Add “scoped” attribute to limit CSS to this component only →<style scoped>h3 {margin: 40px 0 0;}ul {list-style-type: none;padding: 0;}li {display: inline-block;margin: 0 10px;}a {color: #42b983;}</style>

Now, copy this code block below into the template section:

<template><div><h2>The money Game</h2><p>Jack and Jill both won 2 all-access tickets to the Amusement Park </p><p>They both also have $0 each in their pockets and want to play the MG</p><button v-on:click=”jack++”>Add $1 to Jack</button><button v-on:click=”jill++”>Add $1 to Jill</button><p>Jack: ${{jack}}</p> <p>Jill: ${{jill}}</p></div></template>

Run the application in the development server with this line of command in your VS Code terminal:

npm run serve

At this stage, you have to initialize the variables created so that Vue JS can display them without errors. Change the script section in the test.vue file to this:

<script> export default {  name: ‘Test’,  data() {  return {   jack: 0,   jill: 0  } }}</script>

To add styles to the project, copy this into the styles section:

<style scoped>h3 {margin: 40px 0 0;}ul {list-style-type: none;padding: 0;}li {display: inline-block;margin: 0 10px;}a {color: #42b983;}</style>

If you save all and run the application again, you should see the display below

Method Event Handlers

The logic for many event handlers will be more complex though, so keeping your JavaScript in the value of the v-on attribute is not feasible or clean. The v-on directive as you know can accept method names so that you can set your logic in a method and have it still work like it was defined in the template level. Using our little sample demonstration, we can move the logic in the template into a method. Go inside the script section and add the method below:

methods:{ addJack: function(){  this.jack++; }, addJill: function(){  this.jill++; }}

This gives you exactly the same functionality with declaring it in the template level, so by abstracting it with methods, you have a cleaner template focused on only presentation as it was originally designed to.

Your final test.vue file should look like this:

<template>
<div>
<h2>The money Game</h2>
<p>Jack and Jill both won 2 all-access tickets to the Amusement Park </p>
<p>They both also have $0 each in their pockets and want to play the MG</p>
<button v-on:click="addJack()">Add $1 to Jack</button>
<button v-on:click="addJill()">Add $1 to Jill</button>
<p>Jack: ${{jack}}</p> <p>Jill: ${{jill}}</p>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
jack: 0,
jill: 0
}
},
methods:{
addJack: function(){
this.jack++;
},
addJill: function(){
this.jill++;
}
}

}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
button {
background-color: rgb(58, 128, 194);
border: none;
color: white;
padding: 15px 32px;
margin: 5px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
}
</style>

Why use listeners in HTML?

You might be concerned that this whole event listening approach violates the good old rules about “separation of concerns” where presentation should be separated from script for reactivity. It is important to note that since all Vue handler functions and expressions are strictly bound to the ViewModel that’s handling the current view, it won’t cause any maintenance difficulty. In fact, there are several benefits in using v-on:

  1. It’s easier to locate the handler function implementations within your JS code by skimming the HTML template.
  2. Since you don’t have to manually attach event listeners in JS, your ViewModel code can be pure logic and DOM-free. This makes it easier to test.
  3. When a ViewModel is destroyed, all event listeners are automatically removed. You don’t need to worry about cleaning it up yourself.

Conclusion

This is an introduction to events in Vue JS and how they are handled with the Vue v-on directive. It explores the inline method of handling DOM events in the template level and the cleaner way of using methods. You can get the final code for the demonstration here. Happy hacking!

Learn More

--

--

Helping Startups with Webhooks management at Convoy so they can focus on their core product offerings. Twitter:@viclotana