wittgenstein
wittgenstein

Reputation: 4462

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.

Upvotes: 7

Views: 12045

Answers (4)

cambunctious
cambunctious

Reputation: 9572

You can use VueUse useEventListener which automatically removes the listener on unmount.

Example from the docs:

import { useEventListener } from '@vueuse/core';

const element = ref<HTMLDivElement>();
useEventListener(element, 'keydown', (e) => {
  console.log(e.key);
});

Upvotes: 10

In vue 3 script setup it works like this.

<script setup>
import {onMounted, onUnmounted} from "vue";


function yourFunction(event) {
    //do something
}

onMounted(() => {
    window.addEventListener('click', yourFunction)
})

onUnmounted(() => {
    window.removeEventListener('click', yourFunction);
})
</script>

If you figure out how to remove event listeners from anonymous functions, let me know.

Upvotes: 2

Deniz
Deniz

Reputation: 1503

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)

Upvotes: 8

stackoverfloweth
stackoverfloweth

Reputation: 6907

I usually define my event method outside of mounted

onResize() {
    debounce(() => {
        // ...but how to remove the event listener correctly?
        console.log('resize')
        dim.value = getDimensions()
      }, 250))
    })
}

then inside of mounted you can use

onMounted(() => {
  dim.value = getDimensions()
  // adding the event listener...
  window.addEventListener('resize', this.onResize)
})

and inside of beforeUnmount

beforeUnmount(() => {
  window.removeEventListener('resize', this.onResize)
})

Upvotes: 4

Related Questions