Sometimes, we want to prevent the click event from propagating to the parent when clicking a button inside an element with Vue.js.
In this article, we’ll look at how to prevent the click event from propagating to the parent when clicking a button inside an element with Vue.js.
Prevent the Click Event from Propagating to the Parent When Clicking a Button Inside an Element with Vue.js
We can prevent the click event from propagating to the parent when clicking a button inside an element with Vue.js with the self
modifier.
For instance, we can write:
<template>
<div id="app">
<div class="parent" @click.self="showAlert('parent clicked')">
<span class="child" @click="showAlert('child1 clicked')">Child1</span>
<span class="child" @click="showAlert('child2 clicked')">Child2</span>
<span class="child" @click="showAlert('child3 clicked')">Child3</span>
</div>
</div>
</template>
<script>
export default {
name: "App",
methods: {
showAlert(str) {
alert(str);
},
},
};
</script>
<style scoped>
.parent {
padding: 20px;
}
</style>
We add the self
modifier to the @click
directive on the outer div so that the click event will be confined to the parent div.
When we click on each div or span, the showAlert
method will be run.
Conclusion
We can prevent the click event from propagating to the parent when clicking a button inside an element with Vue.js with the self
modifier.