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

how to remove an event listener in vue 3 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>

你会如何删除事件侦听器?

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

我通常在 mounted 之外定义我的事件方法

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

然后在 mounted 里面你可以使用

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

和 beforeUnmount 内部

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

为什么不在 unmounted 生命周期挂钩中 (docs)

window.removeEventListener("resize", debounce);

对于 Vue 3 Composition API 相应的钩子是 onUnmounted(参见 docs