我有一个事件侦听器,可以在安装项目时以及每次调整大小事件后获取视口尺寸。
我不知道如何正确删除事件监听器。
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。
您可以使用 VueUse useEventListener 它会在卸载时自动删除监听器。
文档中的示例:
import { useEventListener } from '@vueuse/core';
const element = ref<HTMLDivElement>();
useEventListener(element, 'keydown', (e) => {
console.log(e.key);
});
我通常在 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)
})
在
vue 3 script setup
中它的工作原理如下。
<script setup>
import {onMounted, onUnmounted} from "vue";
function yourFunction(event) {
//do something
}
onMounted(() => {
window.addEventListener('click', yourFunction)
})
onUnmounted(() => {
window.removeEventListener('click', yourFunction);
})
</script>
如果您知道如何从
anonymous functions
中删除事件侦听器,请告诉我。