I have a code where I click
on a button
and it immediately fires the addEventListener("click")
, I want to prevent it from firing immediately. the normal thing is that I can see the console.log
, until the second click because when I click for the first time I add the listener and after the first time it is already listening to the click events showing console.logs
How can I prevent it?
this is my live code:
<template>
<div id="app">
<button @click="addEvent">add event body</button>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
methods: {
addEvent() {
document.body.addEventListener('click', this.doSomething);
},
doSomething() {
console.log('click');
},
},
};
https://stackblitz.com/edit/vue-fnxvgg?file=src/App.vue
CodePudding user response:
There's a few solutions you can use ! But I believe stopPropagation() will work the best for you! I also added click.once to your addEvent function as I am assuming you would only want to call it to add the event listener!
<template>
<div id="app">
<button @click.once="addEvent">add event body</button>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
methods: {
addEvent(event) {
event.stopPropagation()
document.body.addEventListener('click', this.doSomething);
},
doSomething() {
console.log('click');
},
},
};
</script>
Here's the documentation for reference! https://v2.vuejs.org/v2/guide/events.html#Event-Modifiers https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
CodePudding user response:
You need to use the stop
modifier to achieve this behavior. It is the same as event.stopPropagation()
but it is a vue way of handling events: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
<template>
<div id="app">
<button @click.stop="addEvent">add event body</button>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
methods: {
addEvent() {
console.log('ADDED');
document.body.addEventListener('click', this.doSomething);
},
doSomething() {
console.log('click');
},
},
};
</script>
<style>
body {
height: 100vh;
width: 100vw;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Interactive example: https://stackblitz.com/edit/vue-nknkm9?file=src/App.vue