Vue.js ships with a few pre-defined events that allow you to capture an input from a user’s mouse, be it clicking on an element, hovering over it, scrolling, etc. Using these you can provide a greater level of interaction with your Vue website/web app. In this post I will go over some of these mouse events that you have at your disposal when using Vue.js.
With the use of the v-on directive, you can listen to the user’s input events such as keypresses, mouse events, etc.
The main mouse event that you’ll generally be using is the click event. When you call this, you simply pass in the name of a function to be called upon clicking the element. Here’s an example:
This v-on:click can also be extended further than just listening to a single click. Modifiers can be used to specify the mouse button, for example. v-on:click.left restricts the event to only listen to clicks that are specifically using the left mouse button, v-on:click.right restricts the event to specifically the right mouse button, and v-on:click.middle only listens to a click of the middle mouse button.
A parameter can also be passed into this method to make the value available in the code executed within the method. An example of this is here:
Another way the click event can be extended is with event modifiers which can specify the behaviour of the DOM when executing the events. The event modifiers available to you when using v-on include:
|Will isolate the event to this element and will not listen to click events higher up the DOM tree
|Will prevent the default behaviour of the element this is on
|The event listener will be added in capture mode
|This will only trigger if the target of the event being called is the element itself
|With once, the method will only run once in one instance of the page
These modifiers can be used in conjunction with one another; for example, to use .stop and .prevent on the same event listener, you would use v-on:click.stop.prevent . This will prevent clicks on only this element. The order is an important factor when chaining modifiers. If the order of this was v-on:click.prevent.stop, then the click would be prevented on all of the preceding elements in the DOM tree first, and then the event would be isolated to this specific element.
The mouseover event would be used to call a method when the cursor is hovered over an element. The implementation of this is pretty much identical to the implementation of the click event, only the word mouseover is used instead of click.
The event modifiers (.stop, .prevent, .capture, etc.) explained earlier can also be used on a mouseover event and will behave identically. For example, when using the .prevent modifier on the mouseover event handler, you would use v-on:mouseover.prevent="showAlert" .
For information on the mouse events available to you in Angular 4/5, you can view the article here: