Global event handlers should be properly removed during Vue component lifecycle
- VUE_MISSING_CLEANUP_IN_LIFECYCLE
- Error
- Medium
- vue
This rule applies when global event handlers are added, but not removed properly during the lifecycle of a Vue component.
In general, global handlers added at mounted()
should be explicitly removed at beforeDestroy()
(Vue 2.x) or beforeUnmount()
(Vue 3.x) because they persist beyond the Vue component lifecycle.
If the handler is not removed,
- It can be executed unnecessarily.
- Data reachable from it cannot be garbage-collected and a memory leak would occur.
Currently, this rule detects alarms on the following global handlers:
- Event listeners on the
window
object - Event listeners on the
document
object setInterval()
handlers
Noncompliant Code Example
View with compliant examples side by side<script>
export default {
methods: {
update() {}
},
mounted() {
window.addEventListener('hashchange', this.update, false); // VUE_MISSING_CLEANUP_IN_LIFECYCLE alarm
},
beforeUnmount() {
window.removeEventListener('hashChange', this.update, false); // 'C' is upper-case
}
}
</script>
Compliant Code Example
View with noncompliant examples side by side<script>
export default {
methods: {
update() {}
},
mounted() {
window.addEventListener('hashchange', this.update, false);
},
beforeUnmount() {
window.removeEventListener('hashchange', this.update, false);
}
}
</script>
Version
This rule was introduced in DeepScan 1.28.0.