继续封装,让元素也能使用useScroll插件

241 阅读1分钟

需要传入对应元素,并且判断,不过不传默认是window,第一次判断是否是window,是的话就默认步骤,不是的话就获取元素的属性就行

export default function useScroll(elRef) {
  // 监听window或元素窗口滚动
  let el = window
  const isReachBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)
  const scrollListenerHandler = throttle(() => {
    console.log('监听到滚动')
    if (el === window){
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
    }else{
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
    }
    if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
      console.log('到底部了')
      isReachBottom.value = true
    }
  },1000)

  onMounted(() => {
    if(elRef) { el = elRef.value }
    el.addEventListener('scroll', scrollListenerHandler)
  })
  onUnmounted(() => {
    el.removeEventListener('scroll', scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}

如何使用:

const detailRef = ref()
const { scrollTop } =useScroll(detailRef)

// 给对应元素挂上即可
<div class="detail hide-tabbar" ref="detailRef">