Vue 3的事件修饰符包括:
.stop - 调用 event.stopPropagation(),防止事件冒泡。
.prevent - 调用 event.preventDefault(),阻止事件的默认行为。
.self - 只当事件是从事件绑定的元素本身触发时才触发回调。
.capture - 添加事件侦听器时使用事件捕获模式。
.once - 事件只触发一次。
.passive - 告诉浏览器你不想阻止事件的默认行为。
Vue文档的解释有些抽象,下面通过举例说明。
原始代码如下,当点击链接链接时输出 a 和 div,点击 div 区域时只输出 div。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click="console.log('a')" >点我</a > </div> </template>
|
如果你在子元素上使用 .stop,那么点击子元素时,父元素的点击事件不会被触发。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click.stop="console.log('a')" >点我</a > </div> </template>
|
使用 a 标签时,点击的默认行为是跳转链接,使用 .prevent 可以阻止默认行为。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click.prevent="console.log('a')" >点我</a > </div> </template>
|
使用 .self,点击链接时只会输出 a,冒泡到 div 则不会响应。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click.self="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click.self="console.log('a')" >点我</a > </div> </template>
|
使用 .capture,指向内部元素的事件,在被内部元素处理前,先被外部处理。点击链接,下面的例子会先输出 div 再输出 a。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click.capture="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click="console.log('a')" >点我</a > </div> </template>
|
用 .once 可以让事件只触发一次。这里要注意冒泡,下面的例子中,第一次点击链接,输出 a 和 div,接下来每次点击链接,都还会输出 div。
1 2 3 4 5 6 7 8 9 10
| <template> <div style="background: yellow" @click="console.log('div')"> <a href="https://11d-beyonder.github.io" target="_blank" @click.once="console.log('a')" >点我</a > </div> </template>
|
.passive 用于告诉浏览器不阻止默认行为。此时就有一个问题:默认行为不阻止就会自动执行,这为啥要告诉浏览器?不妨参考这篇文章。典型的例子是用于滚动和缩放。
1
| <div @scroll.passive="onScroll">...</div>
|