vue实现事件捕获
Vue 实现事件捕获的方法
在 Vue 中,默认情况下事件是通过冒泡机制传递的。如果需要实现事件捕获,可以通过原生 DOM 事件的方式或 Vue 的修饰符来实现。
使用原生 DOM 事件
通过 addEventListener 的第三个参数设置为 true,可以启用事件捕获模式。
<template>
<div ref="parent" @click="handleClick">
<div ref="child">Click me</div>
</div>
</template>
<script>
export default {
mounted() {
this.$refs.parent.addEventListener('click', this.handleParentClick, true);
this.$refs.child.addEventListener('click', this.handleChildClick, true);
},
methods: {
handleParentClick() {
console.log('Parent captured');
},
handleChildClick() {
console.log('Child captured');
},
handleClick() {
console.log('Bubbling event');
}
}
}
</script>
使用 Vue 的 .capture 修饰符
Vue 提供了 .capture 修饰符,可以简化事件捕获的实现。
<template>
<div @click.capture="handleParentClick">
<div @click.capture="handleChildClick">Click me</div>
</div>
</template>
<script>
export default {
methods: {
handleParentClick() {
console.log('Parent captured');
},
handleChildClick() {
console.log('Child captured');
}
}
}
</script>
结合 .stop 修饰符阻止冒泡
如果需要在捕获阶段阻止事件继续传递,可以结合 .stop 修饰符。
<template>
<div @click.capture.stop="handleParentClick">
<div @click.capture="handleChildClick">Click me</div>
</div>
</template>
注意事项
- 事件捕获的顺序是从外层到内层,与冒泡的顺序相反。
- 使用
.capture修饰符时,事件处理函数会在捕获阶段触发,而不是默认的冒泡阶段。 - 如果同时使用了
.capture和.stop,事件会在捕获阶段被阻止,不会继续传递到目标元素或冒泡阶段。







