Vue.js for Beginners: Adding event listeners #2

Lets add event listeners such as on click. I this post we will learn how to add event listeners in vue js application

Last time (in part 1 of this series) we figured out how to add Vue to our index.html
with a regular <script> tag, and we managed to add our very first reactive property to the page. Today, let's learn how we can change this property with user input.

Our code so far looks like this:
<html> <head> <title>Vue 101</title> </head> <body> <h1>Hello!</h1> <div id="app"> <p>My local property: {{ myLocalProperty }}</p> </div> <script
</script> <script> const app = new Vue({ el: '#app', data: { myLocalProperty: 'Im a local property value' } }); </script> </body> </html>

Listening to user events

In order to better showcase the reactivity of Vue, and to learn how to react to user events we are going to add a button to our app that will change the value of our myLocalProperty prop.

Go ahead and first add a new button to our <div id="app">.
<div id="app">
<p>My local property: {{ myLocalProperty }}</p>
<button>Click me</button>

Now, how do we react to this button getting clicked?

If you come from a jQuery background your instinct may be to try to do something like this: $('button').click();, however, there's a golden rule in Vue. NEVER manipulate the DOM (elements in the page's HTML) directly.

Without going into super intricate details, Vue keeps a virtual "copy" of your HTML (in this case our div with the "app" ID) and automagically ๐Ÿง™โ€โ™€๏ธ ๐Ÿง™โ€โ™‚๏ธ figures out where and how to update it when properties change.

If you make changes to the DOM directly with JavaScript, you risk losing these changes and unexpected behavior whenever Vue re-renders the content, because it will not be aware of these changes.

Enough theory though, let's move on with the clicking. Add this event handler to our button:
v-on:click="myLocalProperty = 'The button has clicked'"
Click me

A couple of things are happening here.

v-on:click="" In Vue we have these "directives" that we can add to our HTML content.

A directive simply put is an HTML parameter that Vue can understand.
In this particular case, we are telling Vue: Vue (v-), on the user's click do this: "myLocalProperty = 'The button has clicked'".
which is simply an inline declaration to change the value of our property.

If you go ahead and open your index.html file now in the browser and click the button, you will see the string that we interpolated earlier inside the {{ย }} in our code will react to our button modifying the property.

Alternate syntax

In most places you will most likely not find events being set on the HTML with v-on:[eventname] as we have in this example because in Vue we have a very handy shorthand for this type of thing. @[eventname].

Let's change our <button> click even to to use this shorthand:
@click="myLocalProperty = 'The button has been clicked'"
Click me


In most cases, when a user event like the click of a button is fired, you will need to do a lot more than changing the value of a variable. So let's learn about methods (aka, functions).

To continue with our example, let's make the button call a function that will do something really simple, it'll change the value of myLocalProperty by appending a random number to a string.

Delete our previous implementation of @click and replace it with this:
<button @click="buttonClicked">Click me</button>

Notice that we're not adding a () after "buttonClicked". We can omit these when we are not passing any arguments to our function. For example, @click="changeName('Marina')". (More on this later when we look at conditional rendering ๐Ÿ™‚)

Now that we have our button ready to execute buttonClicked on clicks, we need to actually write this function.

Vue has a special place to write functions that our Vue instance can use. This place is inside the {ย } we passed to our new Vue({}) line before.
We will create a methods: {} property that will hold an object filled with our functions.
<script> const app = new Vue({ el: '#app', data: { myLocalProperty: 'Im a local property value' }, methods: { // 1 buttonClicked() { // 2 const newText =
'The new value is: ' +
Math.floor( Math.random() * 100); // 3 this.myLocalProperty = newText; // 4 } } }); </script>

Let's dissect this:
  1. We declare the methods property inside our Vue instance. As I mentioned, in here you will put all your instance methods/functions.
  2. Inside the methods object {ย } we declare buttonClicked(), which is the function we are trying to call on our @click listener. We're not going to use any parameters at this point so empty ().
  3. We join the value of the rounded down value Math.floor of the result of multiplying the random value of 0-1 by 100 to a string and store it in a constant.
  4. We assign the value of our new string to myLocalProperty. Now be very careful about this tiny detail ๐Ÿ™ƒ (lame pun intended). When we assign new values to the properties inside the instance's data property (the one inside data: {}) you MUST access it through this.[prop-name].

In the context of a method the keyword this refers to the Vue instance. Vue will perform some magic behind the scenes so that you can read/write to your properties inside data by doing = value.

Now that we have everything set up, reload your index.html file and click on your button.

The value of our interpolated {{ย }} string on the containing <p> will be updated every time you click the button, for every single time the buttonClicked function is executed.

Once again, the magic of Vue's reactivity is coming into play.
. . .

It's not the same without you

Join the community to find out what other Ednsquare users are discussing, debating and creating.