What comes to your mind when you hear the word, Event?
(Source: giphy)
An event is something that happens, especially something important or unusual. Going to your workplace is an event, boarding a train is an event, taking your food on time is an event, and there are so many events that you perform or witness daily. Talking about Events in web programming. Events are things that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react to these events. In this blog, we will discuss Event Handling in Vue.js using various examples. Let's get started.
Getting Basics Right: What exactly is an Event?
As discussed above, an Event is a thing that happens to HTML elements. It can be something the browser does or something that you as a user do. Some examples are:
An HTML Input Field was changed,
A button was clicked.
The user moves the mouse over an HTML element.
The user pushes a keyboard key.
The browser has finished loading the page.
With JavaScript, you can execute code when certain events occur; you use an Event handler to detect an event and execute a particular piece of code corresponding to an event. Now let's see how to perform Event Handling in Vue.js.
Listening to Events
(Source: tenor)
User interactions with the view can trigger events on the DOM; You can use the v-on directive to listen to the DOM events and run some JavaScript code when they are triggered. The v-on directive can be typically shortened to the @ symbol.
Usage
v-on:click="methodName"
@click="methodName"
Example: Consider the following example where we are implementing a counter that increments every time a user clicks a button. There is an event listener listening to the click event as shown below:
HTML
<div id="basic-event" class="demo">
<button @click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>
Keeping your JavaScript logic in the value of the v-on attribute isn't feasible when dealing with complex logic for event handlers.
The v-on accepts the name of the method you’d like to call upon a particular event. So you can use the name of the method inside the v-on attribute as shown below:
HTML
<div id="event-with-method" class="demo">
<!-- `greet` is the name of a method defined below -->
<button v-on:click="greet">Greet</button>
</div>
When you click the Greet, button a pop up will occur saying Hello Vue.js in the above example.
Methods in Inline Handlers
An alternative to binding directly to the method name is to use methods in an inline JavaScript statement. This is illustrated in the following example.
There are cases when multiple methods need to be executed corresponding to a particular event; for example, when a user submits a form by clicking on the submit button; you need to perform the following tasks:
Inform the user that the form is successfully submitted.
Send the user an email of confirmation.
Ask the user to register for some more events,
There will be different methods corresponding to each of the tasks mentioned above. In that case, you can have multiple methods in an event handler separated by a comma operator. This is illustrated in the below example:
HTML
<!-- both method1() and method2() will execute on button click -->
<button @click="method1($event), method2($event)">
Submit
</button>
Vuejs
// ...
methods: {
method1(event) {
// first handler logic...
},
method2(event) {
// second handler logic...
}
}
You can also try this code with Online Javascript Compiler
The event handlers can have methods like event.preventDefault() or event.stopPropagation() inside them. It can be easily done inside the methods as well. However, it's a good idea to separate them with the data logic. Doing so will make methods purely about data logic rather than having to deal with DOM details. Vue.js effectively addresses this problem by providing event modifiers for v-on. Instead of writing these out in the methods, we can use the modifiers provided with the vue-on directive. These modifiers are directive postfixes denoted by a dot. Some of the event modifiers are listed below:
.prevent
.capture
.once
.stop
.passive
Refer to the example below to understand more about event modifiers.
<!-- the click event's propagation will be stopped -->
<a @click.stop="doThis"></a>
<!-- the submit event will no longer reload the page -->
<form @submit.prevent="onSubmit"></form>
<!-- modifiers can be chained -->
<a @click.stop.prevent="doThat"></a>
<!-- just the modifier -->
<form @submit.prevent></form>
<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div @click.capture="doThis">...</div>
<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div @click.self="doThat">...</div>
You can also try this code with Online Javascript Compiler
A common question that comes to mind is, Is there any difference between @click.prevent.self and @click.self.prevent, or in other words, does the relative ordering of the event modifiers matter?
(Source: giphy)
It is recommended to think about it and try to conclude by yourself. However, we have provided the solution in the FAQs section as well.
Refer to the below code sample that would remove the default behavior of the a tag and just call the addToCount method. If we did not add the modifier, the page would redirect to the path defined in the href attribute.
Except for the .once modifier, which can be used on component events, all modifiers are exclusive to native DOM events.
Key Modifiers
Frequently there is a need to check for specific keys as well in keyboard events. For example, call the submit() method when the key pressed is the enter key, call the close() method, when the key pressed, is the escape key. Using Vue, we can add key modifiers for v-on or @ when listening for key events.
<!-- only call `vm.submit()` when the `key` is `Enter` -->
<input @keyup.enter="submit" />
An alternative way is to use KeyboardEvent.key to directly use any valid key names exposed.
<input @keyup.page-down="onPageDown" />
In the above example, the handler will only be called if $event. the key is equal to 'PageDown.'
System Modifier Keys
There are certain modifiers to trigger mouse or keyboard event listeners only when the corresponding modifier key is pressed. These are called System Modifier Keys, .ctrl, .alt, .shift and .meta are some examples. For example
<!-- Alt + C -->
<input v-on:keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div v-on:click.ctrl="doSomething">Do something</div>
Note that modifier keys are different from regular keys, and when used with keyup events, they have to be pressed when the event is emitted. In other words, keyup.ctrl will only trigger if you release a key while holding down ctrl. It won't trigger if you release the ctrl key alone. If you do want such behavior, use the keyCode for ctrl instead: keyup.17.
Benefits of v-on
At first glance, the event handling approach seems to violate the old rule of separation of concerns. However, it's not the case. The reason is all Vue handler functions, and expressions are strictly bound to the ViewModel that's handling the current view, so there will not be any maintenance difficulties.
We studied Event Handling in Vue, now. Let's check some of the frequently asked questions related to Event Handling.
Frequently Asked Questions
Q1) What is Event Handling?
Ans 1) Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse are the activities that cause an event to happen. Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code, known as an event handler, that is executed when an event occurs.
Q2) Is there any difference between @click.prevent.self and @click.self.prevent, or in other words, does the relative ordering of the event modifiers matter?
Ans 2) Order matters when using modifiers because the relevant code is generated in the same order. Therefore using v-on:click.prevent.self will prevent all clicks while v-on:click.self.prevent will only prevent clicks on the element itself.
Key Takeaways
In this blog, we studied Event Handling in Vue.js. This is an important concept to have a solid grip on.
This doesn’t seem enough, though.
Of course not!
Whether it is frontend or backend or even both, Web development is all about learning by doing. So next, you should try making out some basic projects on your own. You can always refer to Coding Ninjas Studio for many resources in the form of Guided Paths, Blogs, and Interview Experiences.