vue.jsevent-listenervuejs3vue-composition-apiremoveeventlistener

how to remove an event listener in vue 3 correctly


I have an event listener that gets the viewport dimensions when the project is mounted and after each resize event.

I don't know how to remove the event listener correctly.

const { createApp, onMounted, ref } = Vue;
const app = createApp({
  setup() {
    const dim = ref({})
    
    onMounted(() => {
      dim.value = getDimensions()
      // adding the event listener...
      window.addEventListener('resize', debounce(() => {
        // ...but how to remove the event listener correctly?
        console.log('resize')
        dim.value = getDimensions()
      }, 250))
    })
    
    function getDimensions () {
      return {
        w: window.innerWidth,
        h: window.innerHeight
      }
    }
    
    // generic debounce function
    function debounce (func, wait) {
    let timeout
    return function executedFunction (...args) {
      const later = () => {
      timeout = null
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    }

    return {
      dim
    }
  }
});
app.mount("#app");
.navbar {
  position: fixed;
  width: 100%;
  height: 50px;
  top: 0;
  left: 0;
  background-color: #555;
  text-align: center;
}
p {
    color: #fff;
}
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <div class="navbar">
    <p>
      <span>width: {{ dim.w + ' ' }}</span>
      <span>| height: {{ dim.h }}</span>
    </p>
  </div>
</div>

How would you remove the event listener?

I am using Vue 3 with the composition API.


Solution

  • why not in a unmounted life cycle hook (docs)

    window.removeEventListener("resize", debounce);
    

    For Vue 3 Composition API the respective hook is onUnmounted (see the docs)