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 onMounted() should be explicitly removed at onBeforeUnmount() 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
windowobject - Event listeners on the
documentobject setInterval()handlers
Noncompliant Code Example
View with compliant examples side by side<script setup>
import { onMounted, onBeforeUnmount } from 'vue';
function update() { doSomething(); }
onMounted(() => {
window.addEventListener('hashchange', update, false); // VUE_MISSING_CLEANUP_IN_LIFECYCLE alarm
})
onBeforeUnmount(() => {
window.removeEventListener('hashChange', update, false); // 'C' is upper-case
})
</script>Compliant Code Example
View with noncompliant examples side by side<script setup>
import { onMounted, onBeforeUnmount } from 'vue';
function update() { doSomething(); }
onMounted(() => {
window.addEventListener('hashchange', update, false);
})
onBeforeUnmount(() => {
window.removeEventListener('hashchange', update, false);
})
</script>Version
This rule was introduced in DeepScan 1.28.0.