什么是事件侦听器上的捕获模式

vue.js Vue.js

猴子Harry路易

2020-03-17

在vue文档的“ 事件修饰符”下,有一个名为的修饰符的示例,capture其声明如下:

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

我已经进行了一些搜索,但是还没有找到明确的答案,它如何修改事件绑定,于是我心想:“您知道谁总是有答案吗?堆栈溢出'

第1878篇《什么是事件侦听器上的捕获模式》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
小胖阿飞 2020.03.17

因此,发布后,我偶然发现了这篇文章,内容清楚。假设在此示例中,您将三个元素嵌套在一起:

<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 call doThis(...) three times, the first from .outer, the second from .middle, and the third from .inner.

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 call doThis(...) two times, the first from .outer and the second from .middle

梅小卤蛋梅 2020.03.17

元素上的冒泡事件处理程序和捕获事件处理程序都将被触发一次,不同之处在于它们被触发的时间(子代之前之后)。捕获模式意味着在子元素上的任何处理程序之前触发处理程序。冒泡模式(默认),意味着在所有子元素完成其处理程序后触发处理程序。您甚至可以通过执行以下操作来放置捕获模式和冒泡模式事件处理程序:<div v-on:click="doThis" v-on:click.capture="doThis">

JS小提琴演示了如何单击嵌套的内部元素首先如何以“从外到内”的顺序触发捕获处理程序,然后以“从内到外”的顺序触发气泡处理程序。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android