vue3如何監(jiān)聽頁面的滾動
有的時候監(jiān)聽的是window的滾動,有的時候是監(jiān)聽元素的滾動。
我們可以先創(chuàng)建一個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 }
}
可以傳入元素實例參數(shù)elRef,如果沒有傳入的話就初始化為window。

在掛載完成之后判斷是否傳入了元素實例elRef,如果有的話就使用元素實例,監(jiān)聽元素的滾動。

還需修改window還是元素滾動的判定。
下面是使用這個hook的方法。

使用ref取到需要滾動的元素實例。將取到的元素實例傳入到useScroll中。

使用useScroll這個hook,取出scrollTop的值進行判斷。
總結
到此這篇關于vue3如何監(jiān)聽頁面的滾動的文章就介紹到這了,更多相關vue3監(jiān)聽頁面滾動內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue2.0使用v-for循環(huán)制作多級嵌套菜單欄
這篇文章主要介紹了vue2.0制作多級嵌套菜單欄,主要使用v-for循環(huán)生成一個多級嵌套菜單欄,這個方法應用非常廣泛,需要的朋友可以參考下2018-06-06
vue3中echarts的tooltip組件不顯示問題及解決
這篇文章主要介紹了vue3中echarts的tooltip組件不顯示問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
Vuex state中同步數(shù)據和異步數(shù)據方式
這篇文章主要介紹了Vuex state中同步數(shù)據和異步數(shù)據方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

