let scrollTop = ref(0)
let oldScrollTop = ref(0)
const fn = () => {
scrollTop.value = window.scrollY
}
/**
* 滚动到底部加载更多
*/
onMounted(() => {
window.addEventListener('scroll', fn, true);
})
/**
* 滚动到底部加载更多,离开当前组件时移除事件监听器
*/
onBeforeUnmount(() => {
// 屏幕复位
window.scroll(0,0)
window.removeEventListener('scroll', fn, true)
})
watch(
() => scrollTop1.value,
(newValue, oldValue) => {
setTimeout(() => {
if (newValue === window.scrollY) {
if (hasScrolled()) {
findSth()
}
}
}, 20)
}
/**
* 判断是否滚动到底部
*/
function hasScrolled () {
// 变量scrollTop是滚动条滚动时,距离顶部的距离
let st = document.documentElement.scrollTop || document.body.scrollTop
//变量clientHeight是可视区的高度
let clientHeight = document.documentElement.clientHeight
//变量scrollHeight是滚动条的总高度
let scrollHeight = document.documentElement.scrollHeight
let bottomOfWindow = (st + clientHeight) > scrollHeight - 1
// 判断是否滚动到底部
if (st != 0 && bottomOfWindow) {
return true
}
}
本文探讨了在前端开发中遇到的一个问题:`window.removeEventListener`在组件卸载时失效。文章介绍了如何在Vue组件中监听窗口滚动事件,并在离开组件时正确移除事件监听器。同时,还提供了一个`hasScrolled`函数来判断是否滚动到底部,以实现滚动到底部加载更多的功能。在`onBeforeUnmount`钩子中,使用`window.scroll`进行屏幕复位,并尝试移除滚动事件监听器,确保内存泄漏不会发生。
903

被折叠的 条评论
为什么被折叠?



