We now have a youtube channel. Subscribe!

Vue.js | Events

Vue.js | Events


Hello folks! Welcome back to a new edition of our tutorial on Vue.js. In this tutorial, we are going to be discussing about Events in Vue.js.

v-on is the attribute that's added to the DOM elements to listen to the events in Vue.js.

Click Event

Example

Following is a simple example -

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <button v-on:click = "displaynumbers">Click ME</button>
         <h2> Add Number 100 + 200 = {{total}}</h2>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               num1: 100,
               num2 : 200,
               total : ''
            },
            methods : {
               displaynumbers : function(event) {
                  console.log(event);
                  return this.total =  this.num1+ this.num2;
               }
            },
         });
      </script>
   </body>
</html>

Output

Events

The following code is used to assign a click event for the DOM element.

<button v-on:click = "displaynumbers">Click ME</button>

There is a shorthand for v-on, meaning that we can also call the event as follows -

<button @click = "displaynumbers">Click ME</button>

On the click of the button, it is going to call the method displaynumbers, which takes in the event and we've consoled the same in the browser as shown above.

We are now going to check one more event mouseover mouseout.

Example

Following is a simple example -

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <div v-bind:style = "styleobj" v-on:mouseover = "changebgcolor" v-on:mouseout = "originalcolor"></div>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               num1: 100,
               num2 : 200,
               total : '',
               styleobj : {
                  width:"100px",
                  height:"100px",
                  backgroundColor:"red"
               }
            },
            methods : {
               changebgcolor : function() {
                  this.styleobj.backgroundColor = "green";
               },
               originalcolor : function() {
                  this.styleobj.backgroundColor = "red";
               }
            },
         });
      </script>
   </body>
</html>

In the above example, we have created a div with width and height as 100px. It has been given a background color red. On mouseover we are changing the color to green, and on mouseout we're changing the color back to red.

Thus, during mouseover, a method is called changebgcolor and as soon as we move the mouse out of the div tag, a method is called originalcolor.

This is done as follows -

<div v-bind:style = "styleobj" v-on:mouseover = "changebgcolor" v-on:mouseout = "originalcolor"></div>


Two events - mouseover and mouseout - is assigned to the div as shown above. We've created a styleobj variable and specified the required style to be assigned to the div. The same variable is binded to the div using v-bind:style = "styleobj".

In changebgcolor, we're changing the color to green using the following code.

changebgcolor : function() {
   this.styleobj.backgroundColor = "green";
}

Using the styleobj variable, we are changing the color to green.

Likewise, the below code is used to change it back to the original color.

originalcolor : function() {
   this.styleobj.backgroundColor = "red";
}

Output

The following will be the output in the web browser.


When we mouseover, the color will change to green as shown in the screenshot below.


Event Modifiers

Vue has event modifiers available on v-on attribute. Following below are the modifiers available -

.once

Allows the event to execute only once.

Syntax

<button v-on:click.once = "buttonclicked">Click Once</button>

We need to put in dot operator while calling the modifiers as shown in the above syntax. Let us use it in an example and understand the working of the once modifier.

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <button v-on:click.once = "buttonclickedonce" v-bind:style = "styleobj">Click Once</button>
         Output:{{clicknum}}
         <br/><br/>
         <button v-on:click = "buttonclicked"  v-bind:style = "styleobj">Click Me</button>
         Output:{{clicknum1}}
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               clicknum : 0,
               clicknum1 :0,
               styleobj: {
                  backgroundColor: '#2196F3!important',
                  cursor: 'pointer',
                  padding: '8px 16px',
                  verticalAlign: 'middle',
               }
            },
            methods : {
               buttonclickedonce : function() {
                  this.clicknum++;
               },
               buttonclicked : function() {
                  this.clicknum1++;
               }
            }
         });
      </script>
   </body>
</html>

Output

event_modifier

In the above example, we have created two buttons. The button with a Click Once label has added the once modifier and the other button is without any modifier. The buttons are defined as follows.

<button v-on:click.once = "buttonclickedonce" v-bind:style = "styleobj">Click Once</button>
<button v-on:click = "buttonclicked"  v-bind:style = "styleobj">Click Me</button>

The first button calls the method known as "buttonclickedonce" and the second button calls the method "buttonclicked".

buttonclickedonce : function() {
   this.clicknum++;
},
buttonclicked : function() {
   this.clicknum1++;
}

Two variables are defined in the clicknum and clicknum1. Both are incremented when the button is clicked. Both the variables are initialized to 0 and the display is seen in the output above.

On the click of the first button, the variable clicknum increments by 1. On the next click, the number isn't incremented as the modifier prevents it from performing any action item assigned on the click of the button.

On the click of the second button, the same action is implemented, that is the variable is incremented. On every single click, the value is incremented and displayed.

Output

Following below is the output we get in the browser.



.prevent

Syntax

<a href = "http://www.google.com" v-on:click.prevent = "clickme">Click Me</a>

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <a href = "http://www.google.com" v-on:click = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               clicknum : 0,
               clicknum1 :0,
               styleobj: {
                  color: '#4CAF50',
                  marginLeft: '20px',
                  fontSize: '30px'
               }
            },
            methods : {
               clickme : function() {
                  alert("Anchor tag is clicked");
               }
            }
         });
      </script>
   </body>
</html>

Output

click_me

If we click on the clickme link, it will send an alert as 'Anchor tag is clicked' and it's going to open the link https://www.google.com in a new tab in your web browser as shown in the following screenshots below.

tag_clicked


tag_opened

Now this works as a normal way, i.e. the link opens up as we want. In case we don't want the link to open up, then we need to include a modifier 'prevent' to the event as shown in the following code.

<a href = "http://www.google.com" v-on:click.prevent = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>

Once added, if we click on the button, it will send an alert message and will not open the link anymore. The prevent modifier prevents the link from opening and only executes the method assigned to the tag.

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <a href = "http://www.google.com" v-on:click.prevent = "clickme" target = "_blank" v-bind:style = "styleobj">Click Me</a>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               clicknum : 0,
               clicknum1 :0,
               styleobj: {
                  color: '#4CAF50',
                  marginLeft: '20px',
                  fontSize: '30px'
               }
            },
            methods : {
               clickme : function() {
                  alert("Anchor tag is clicked");
               }
            }
         });
      </script>
   </body>
</html>

Output


On the click of the link, it will show the alert message and does not open the url again.


Event - Key Modifiers

Vue.js offers key modifiers based on which we can control the event handling. Consider we have a textbox and we want the method to be called only when we press Enter. We can do so by including key modifiers to the events as follows.

Syntax

<input type = "text" v-on:keyup.enter = "showinputvalue"/>

The key that we want to apply to our event is V-on.eventname.keyname (as shown in the above syntax).

We can make use of multiple keynames. For example, V-on.keyup.ctrl.enter.

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <input type = "text" v-on:keyup.enter = "showinputvalue" v-bind:style = "styleobj" placeholder = "Enter your name"/>
         <h3> {{name}}</h3>
      </div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
               name:'',
               styleobj: {
                  width: "30%",
                  padding: "12px 20px",
                  margin: "8px 0",
                  boxSizing: "border-box"
               }
            },
            methods : {
               showinputvalue : function(event) {
                  this.name=event.target.value;
               }
            }
         });
      </script>
   </body>
</html>

Output

multiple_keynames

Type something in the textbox and we will see that it is displayed only when we press Enter.

type_text

Custom Events

Parent can pass data to its component via the prop attribute, nevertheless, we need to tell the parent when there're changes in the child component. For this, we can make use of custom events.

The parent component can listen to the child component event using v-on attribute.

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding">
         <div id = "counter-event-example">
            <p style = "font-size:25px;">Language displayed : <b>{{ languageclicked }}</b></p>
            <button-counter
            v-for = "(item, index) in languages"
            v-bind:item = "item"
            v-bind:index = "index"
            v-on:showlanguage = "languagedisp"></button-counter>
         </div>
      </div>
      <script type = "text/javascript">
         Vue.component('button-counter', {
            template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
            data: function () {
               return {
                  counter: 0
               }
            },
            props:['item'],
            methods: {
               displayLanguage: function (lng) {
                  console.log(lng);
                  this.$emit('showlanguage', lng);
               }
            },
         });
         var vm = new Vue({
            el: '#databinding',
            data: {
               languageclicked: "",
               languages : ["Java", "PHP", "C++", "C", "Javascript", "C#", "Python", "HTML"]
            },
            methods: {
               languagedisp: function (a) {
                  this.languageclicked = a;
               }
            }
         })
      </script>
   </body>
</html>

Output

custom_event


The above example shows the data transfer that involves the parent component and the child component.

The component is created via the following code.

<button-counter
   v-for = "(item, index) in languages"
   v-bind:item = "item"
   v-bind:index = "index"
   v-on:showlanguage = "languagedisp">
</button-counter>

There's a v-for attribute, which will loop with the languages array. The array has a list of languages in it. We need to send the details to the child component. The array values are stored in the item and the index.

v-bind:item = "item"
v-bind:index = "index"

To refer to the values of the array, we need to bind it first to a variable and the variable is referred using props property as follows.

Vue.component('button-counter', {
   template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
   data: function () {
      return {
         counter: 0
      }
   },
   props:['item'],
   methods: {
      displayLanguage: function (lng) {
         console.log(lng);
         this.$emit('showlanguage', lng);
      }
   },
});

The props property contains the item in an array form. We can also refer to the index as -

props:[‘item’, index’]

There is also an event that is added to the component as follows -

<button-counter
   v-for = "(item, index) in languages"
   v-bind:item = "item"
   v-bind:index = "index"
   v-on:showlanguage = "languagedisp">
</button-counter>

The name of the event is showlanguage and it calls a method called languagedisp which is defined in the Vue instance.

In the component, the template is defined as follows -

template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',

There's a button created. The button will get created with as many count in the language array. On the click of the button, there is a method known as displayLanguage and the button clicked item is passed as a param to the function. The component needs to send the clicked element to the parent component for display which is done as follows -

Vue.component('button-counter', {
   template: '<button v-on:click = "displayLanguage(item)"><span style = "font-size:25px;">{{ item }}</span></button>',
   data: function () {
      return {
         counter: 0
      }
   },
   props:['item'],
   methods: {
      displayLanguage: function (lng) {
         console.log(lng);
         this.$emit('showlanguage', lng);
      }
   },
});

The method displayLanguage from above code calls this.$emit('showlanguage', lng);

$emit is used to call the parent component method. The method showlanguage is the event name given on the component using v-on.

<button-counter
   v-for = "(item, index) in languages"
   v-bind:item = "item"
   v-bind:index = "index"
   v-on:showlanguage = "languagedisp">
</button-counter>

We're passing a parameter, i.e. the name of the language that's clicked to the method of the main parent vue instance which's defined as follows -

var vm = new Vue({
   el: '#databinding',
   data: {
      languageclicked: "",
      languages : ["Java", "PHP", "C++", "C", "Javascript", "C#", "Python", "HTML"]
   },
   methods: {
      languagedisp: function (a) {
         this.languageclicked = a;
      }
   }
})

Here, the emit triggers showlanguage which calls the languagedisp method from the Vue instance methods. It assigns the language clicked value to the variable languageclicked and the same is displayed in the browser as shown in the following screenshot.

<p style = "font-size:25px;">Language displayed : <b>{{ languageclicked }}</b></p>

Following is the output we get in the web browser.

language_display


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be discussing about Vue.js Rendering.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain