DOM Event 天生具有 Event Propagation 特性,Vue 提供了 stop
Event Modifier,讓我們在 HTML Template 就能以 Declarative 形式阻止 Event 往外層傳遞。
Version
Vue 2.6.11
Tailwind CSS 1.8.10
Event Propagation
按下 Click Me
,會發現 內
、中
、外
3 個 click
event 都會被觸發,這正是其 Event Propagation 特性。
當按下綠色部分,會發現只有 中
與 外
2 個 click
event 都會被觸發,內
則不觸發,因為 Event Propagation 只會向外,而不會向內。
<template>
<div @click="onOuterClick" class="p-3 bg-blue-500">
<div @click="onMiddleClick" class="p-3 bg-green-500">
<div @click="onInnerClick" class="bg-red-500">Click Me</div>
</div>
</div>
</template>
<script>
let onOuterClick = function() {
console.log('Outer click')
}
let onMiddleClick = function() {
console.log('Middle click')
}
let onInnerClick = function() {
console.log('Inner click')
}
export default {
methods: {
onOuterClick,
onMiddleClick,
onInnerClick
}
}
</script>
第 2 行
<div @click="onOuterClick" class="p-3 bg-blue-500">
<div @click="onMiddleClick" class="p-3 bg-green-500">
<div @click="onInnerClick" class="bg-red-500">Click Me</div>
</div>
</div>
三層 <div>
的 click
event 都有其 event handler,因此能觀察 Event Propagation,且每個 <div>
都增加其 padding 方便 click。
event.stopPropagation()
按下 Click Me
,只有 內
的 click
event 會被觸發。
<template>
<div @click="onOuterClick" class="p-3 bg-blue-500">
<div @click="onMiddleClick" class="p-3 bg-green-500">
<div @click="onInnerClick" class="bg-red-500">Click Me</div>
</div>
</div>
</template>
<script>
let onOuterClick = function() {
console.log('Outer click')
}
let onMiddleClick = function() {
console.log('Middle click')
}
let onInnerClick = function(event) {
console.log('Inner click')
event.stopPropagation()
}
export default {
methods: {
onOuterClick,
onMiddleClick,
onInnerClick
}
}
</script>
18 行
let onInnerClick = function(event) {
event.stopPropagation()
console.log('Inner click')
}
傳統會使用 event.stopPropagation()
阻止 Event Propagation。
Stop Modifier
<template>
<div @click="onOuterClick" class="p-3 bg-blue-500">
<div @click="onMiddleClick" class="p-3 bg-green-500">
<div @click.stop="onInnerClick" class="bg-red-500">Click Me</div>
</div>
</div>
</template>
<script>
let onOuterClick = function() {
console.log('Outer click')
}
let onMiddleClick = function() {
console.log('Middle click')
}
let onInnerClick = function() {
console.log('Inner click')
}
export default {
methods: {
onOuterClick,
onMiddleClick,
onInnerClick
}
}
</script>
第 2 行
<div @click="onOuterClick" class="p-3 bg-blue-500">
<div @click="onMiddleClick" class="p-3 bg-green-500">
<div @click.stop="onInnerClick" class="bg-red-500">Click Me</div>
</div>
</div>
Vue 提供了 stop
event modifier,讓我們在 HTML template 就能阻止 Event Propagation,不必寫 JavaScript。
Conclusion
stop
event modifier 讓我們以 declarative 方式阻止 Event Propagation,不必特別寫 JavaScript