Modifiers for Custom Events
Learn how to use event modifiers with custom events and find out about their use cases.
We'll cover the following
Custom events are a staple of flexible Vue components. They help us write more meaningful code and abstract logic away. Event modifiers are helpful to alter the behavior of events and steer how they work. Let’s combine the two.
Motivation and use cases
Multi-device support has become a standard in today’s web development. People use web apps with smartphones on public transport, laptops and desktop devices at work, and tablets at home. As a result, power-user applications with many shortcuts that make heavy use of keyboard-based event modifiers might not always work the way we want them to.
Imagine a Vue app that offers different data views. These can be opened in a browser-like fashion with tabs to keep track of different views at once. The user can navigate between different data views by clicking links within them. For example, a standard click would open one tab, and a “Ctrl+Click” would open a separate one.
Implementing the difference between a standard click and a “Ctrl+Click” involves adding an extra event listener with a system key modifier. Touch devices don’t offer a “Ctrl+Click” though, essentially locking away this part of the functionality.
How to use modifiers with custom events
First, let’s look at how the Vue compiler handles checks for event modifiers. When we search through Vue’s source code, we‘ll find the file vue/src/compiler/codegen/events.js
, which contains all the code for generating event handles. We’ll also find the relevant lines below:
Get hands-on with 1400+ tech skills courses.