Understanding the .capture
modifier in Vue
The .capture modifier in Vue.js is used to register an event listener in capture mode, as opposed to the default bubble mode.
Event Propagation in the DOM
In the browser’s DOM, events propagate through two main phases:
- Capture Phase: The event travels from the root element down to the target element.
- Bubble Phase: After reaching the target, the event bubbles back up from the target to the root.
By default, Vue (like the DOM itself) listens for events during the bubble phase. For example, if you have a parent and a child element and you click the child, the event will trigger first on the child and then bubble up to the parent.
Using .capture
in Vue
When you add the .capture
modifier to an event listener, you are telling Vue to listen during the capture phase instead. This means the event handler on the parent element will run before the event reaches the child.
<template>
<div v-on:click.capture="parentClickHandler">
<button v-on:click="childClickHandler">Click Me</button>
</div>
</template>
What Happens Here?
When the button is clicked:
parentClickHandler
will run first, because the parent is listening in the capture phase.childClickHandler
will run after, during the bubble phase.
If you remove the .capture
modifier, the default behaviour will apply: the child handler runs first, then the parent’s handler.
When Should You Use .capture?
Using .capture
is helpful in scenarios where:
- You need to handle an event before it reaches a child component or element.
- You want to intercept or analyse the event early in the propagation cycle.
- You need fine-grained control over event order in complex component hierarchies.
It provides additional control over how and when your event handlers are triggered, which can be especially valuable in large Vue applications with nested components.
What you should take from this article
The .capture
modifier gives you access to the capture phase of event propagation, allowing you to manage the timing and flow of events with greater precision. It’s a powerful tool for situations where the order of event handling matters. Consider using it when you need to intercept events early in their lifecycle.