Vue.js event listener leaks can happen when you're not properly removing event listeners from DOM elements when they are no longer needed. Here is how to fix them:
// Don’t forget to remove your event listener when you’re done
this.$refs['myElement'].removeEventListener('click', this.handleClick);
// If the handler is defined in data or computed
data() {
return {
eventHandler: null,
};
},
computed: {
isActiveComputed() {
if (!this.eventHandler) {
this.eventHandler = () => console.log('Event fired!');
document.addEventListener('click', this.eventHandler);
}
return true;
},
},
// You could use a watcher to remove the event listener when it's not needed anymore
watch: {
isActiveComputed(newVal, oldVal) {
if (oldVal && !newVal) {
document.removeEventListener('click', this.eventHandler);
}
},
},
// Or use a method to remove the event listener
methods: {
handleClick() {
console.log('Event fired!');
},
teardown() {
if (this.$refs['myElement']) {
this.$refs['myElement'].removeEventListener('click', this.handleClick);
}
},
},
// Don’t forget to call the teardown method when component is destroyed
beforeDestroy() {
this.teardown();
}
In each case, we're adding an event listener to a DOM element and removing it when it's no longer needed. The most important part is that we remove the event listener from the exact same DOM element where we added it. This.$refs['myElement'] returns the reference to the DOM element in Vue.js.
Don’t forget to call this method when your component is destroyed, as well, to avoid memory leaks.