vue3如何监听页面的滚动
作者:至尊绝伦
这篇文章主要给大家介绍了关于vue3如何监听页面的滚动的相关资料,在vue中实现滚动监听和原生js无太大差异,文中通过图文介绍的非常详细,需要的朋友可以参考下
有的时候监听的是window的滚动,有的时候是监听元素的滚动。
我们可以先创建一个hook。useScroll.js
import { onMounted,onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'
export default function useScroll(elRef){
let el = window
const isReachBottom = ref(false)
const clientHeight = ref(0)
const scrollTop = ref(0)
const scrollHeight = ref(0)
const scrollListenerHandler = throttle(() => {
if(el === window){
clientHeight.value = document.documentElement.clientHeight
scrollHeight.value = document.documentElement.scrollHeight
scrollTop.value = document.documentElement.scrollTop
}else {
clientHeight.value = el.clientHeight
scrollTop.value = el.scrollTop
scrollHeight.value = el.scrollHeight
}
if(clientHeight.value + scrollTop.value >= scrollHeight.value){
// homeStore.fetchHouselistData()
isReachBottom.value = true
}
}, 100)
onMounted(()=> {
if(elRef) {
el = elRef.value
}
el.addEventListener("scroll", scrollListenerHandler)
})
onUnmounted(()=>{
el.removeEventListener("scroll", scrollListenerHandler)
})
return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}
可以传入元素实例参数elRef,如果没有传入的话就初始化为window。

在挂载完成之后判断是否传入了元素实例elRef,如果有的话就使用元素实例,监听元素的滚动。

还需修改window还是元素滚动的判定。
下面是使用这个hook的方法。

使用ref取到需要滚动的元素实例。将取到的元素实例传入到useScroll中。

使用useScroll这个hook,取出scrollTop的值进行判断。
总结
到此这篇关于vue3如何监听页面的滚动的文章就介绍到这了,更多相关vue3监听页面滚动内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
