如何正确删除 vue 3 中的事件监听器

wit*_*ein 7 event-listener vue.js removeeventlistener vuejs3 vue-composition-api

我有一个事件侦听器,可以在安装项目时以及每次调整大小事件之后获取视口尺寸。

我不知道如何正确删除事件侦听器。

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");
Run Code Online (Sandbox Code Playgroud)
.navbar {
  position: fixed;
  width: 100%;
  height: 50px;
  top: 0;
  left: 0;
  background-color: #555;
  text-align: center;
}
p {
    color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

您将如何删除事件侦听器?

我正在使用 Vue 3 和组合 API。

Den*_*niz 8

为什么不在unmounted生命周期挂钩中(文档

window.removeEventListener("resize", debounce);
Run Code Online (Sandbox Code Playgroud)

对于 Vue 3 Composition API,相应的钩子是onUnmounted(请参阅文档


cam*_*ous 6

您可以使用 VueUse useEventListener它会在卸载时自动删除侦听器。

文档中的示例:

import { useEventListener } from '@vueuse/core'

const element = ref<HTMLDivElement>()
useEventListener(element, 'keydown', (e) => {
  console.log(e.key)
})
Run Code Online (Sandbox Code Playgroud)