vue3怎么监听页面的滚动

有的时候监听的是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中。

扫描二维码关注公众号,回复: 14971916 查看本文章

使用useScroll这个hook,取出scrollTop的值进行判断。

猜你喜欢

转载自blog.csdn.net/m0_51636525/article/details/127408775