top of page

Vue.js Events and Rendering

Vue.js Events

We can use the v-on directive to listen to DOM events and run some JavaScript when they’re triggered.

There are various HTML events. Here are a lists of some common events:

Click Event

We are going to explore it with the help of an example


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

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


On clicking the button, it will call the method ‘displaynumbers’, which takes in the event and display the result in the browser as shown in the below image.

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 adding key modifiers to the events as follows


<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 above.

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



When we type something in the textbox, we will see it is displayed once we press Enter.

Vue.js Conditional Rendering

We will work on a example first to explain the details for conditional rendering. With conditional rendering, we want to output only when the condition is met and the conditional check is done with the help of if, if-else, if-else-if, show, etc.




In the above example, we have created a button and two h1 tags with the message.

A variable called show is declared and initialized to a value true. It is displayed close to the button. On the click of the button, we are calling a method showdata, which toggles the value of the variable show. This means on the click of the button, the value of the variable show will change from true to false and false to true.

We have assigned if to the h1 tag as shown in the following code snippet.

<button v-on:click = "showdata" v-bind:style="styleobj">Click Me</button> 				<h1 v-if="show">This is h1 tag</h1>

Now what it will do is, it will check the value of the variable show and if its true the h1 tag will be displayed. Click the button and view in the browser, as the value of the show variable changes to false, the h1 tag is not displayed in the browser. It is displayed only when the show variable is true.

Following is the display in the browser.

If you have any queries regarding this blog or need any help you can contact us on:
6 views0 comments


bottom of page