vue.js

what is capture mode on an event listener


In the vue docs under Event Modifiers, there's an example of a modifier called capture which states the following:

<!-- use capture mode when adding the event listener -->
<div v-on:click.capture="doThis">...</div>

I've done some searching, but haven't found a clear answer as to how this modifies the event binding, then I thought to myself 'You know who always has the answer? Stack Overflow'


Solution

  • So right after posting I stumbled on this article which illustrates it clearly. Let's say for this example that you have three elements nested within each other:

    <div class="outer">
        <div class="middle">
            <div class="inner"></div>
        </div>
    </div>
    

    When a click event occurs, there are two phases: the first is called capturing, the second is called bubbling. When you click on the .inner, the event traverses down from the outermost container element .outer, to .middle, then to .inner in the capturing phase, then from .inner to .middle, then to .outer in the bubbling phase.

    If capture is set on .inner for a click event handler:

    <div class="outer">
        <div class="middle">
            <div class="inner" v-on:click.capture="doThis"></div>
        </div>
    </div>
    

    and you click on it, it will hit .outer, then .middle, then .inner in the capture phase, which will cause doThis(...) to be called, after which the bubbling phase begins.

    If capture is set on .middle for a click event handler

    <div class="outer">
        <div class="middle" v-on:click.capture="doThis">
            <div class="inner"></div>
        </div>
    </div>
    

    and you click on it, it will hit .outer, then .middle, in the capture phase, which will cause doThis(...) to be called, then hit .inner in the capture phase, after which the bubbling phase begins.

    Edit: Thanks for all the great responses below, I've amended the answer to fix where I was incorrect.