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() because they persist beyond the Vue component lifecycle.

If the handler is not removed,

  1. It can be executed unnecessarily.
  2. Data reachable from it cannot be garbage-collected and a memory leak would occur.

Currently, this rule detects alarms on the following global handlers:

  1. Event listeners on the window object
  2. Event listeners on the document object
  3. 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
    },
    beforeDestroy() {
      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);
    },
    beforeDestroy() {
      window.removeEventListener('hashchange', this.update, false);
    }
  }
</script>

Version

This rule was introduced in DeepScan 1.28.0.