How to remove event listener from Vue Component
Solution 1:
You can use this.$el
for whole component and destroy event like you created it:
Vue.component('Child', {
template: `
<div class="child">
click for event
</div>
`,
mounted() {
this.$el.addEventListener('click', (evt) => {
this.handleClickEvent(evt)
})
},
beforeDestroy() {
console.log('distroyed')
this.$el.removeEventListener('click', (evt) => {
this.handleClickEvent(evt)
})
},
methods: {
handleClickEvent(evt) {
console.log(evt.currentTarget)
// do stuff with (evt)
},
},
})
new Vue({
el: "#demo",
data() {
return {
show: true
}
},
methods: {
toggleShow() {
this.show = !this.show
}
}
})
.child {
height: 150px;
width: 200px;
background: goldenrod;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div>
<button @click="toggleShow">mount/unmount component</button>
<Child v-if="show" />
</div>
</div>