vue-监听滚动函数

不建议监听window滚动 建议监听元素滚动 不然每个页面滚动到底部都会触发

import { onDeactivated, onMounted, onUnmounted, ref } from 'vue';
import { throttle } from 'underscore'
//监听滚动位置执行回调函数
// console.log(throttle)
// export default function useScroll(reachBottomCB) {
//   const scrollListenerHandler = () => {
//     const clientHeight = document.documentElement.clientHeight
//     const scrollTop = document.documentElement.scrollTop
//     const scrollHeight = document.documentElement.scrollHeight
//     console.log("-------")
//     if (clientHeight + scrollTop >= scrollHeight) {
//       console.log("滚动到底部了")
//       if (reachBottomCB) reachBottomCB()
//     }
//   }
  
//   onMounted(() => {
//     window.addEventListener("scroll", scrollListenerHandler)
//   })
  
//   onUnmounted(() => {
//     window.removeEventListener("scroll", scrollListenerHandler)
//   })
// }

export default function useScroll(elRef) {
// 传过来一个元素实例(elRef)可以不传,不传默认就是window
// 默认是window
  let el = window

  const isReachBottom = ref(false)
// 元素的内部高度
  const clientHeight = ref(0)
//滚动高度
  const scrollTop = ref(0)
// 视口高度
  const scrollHeight = ref(0)

  // 防抖/节流
  const scrollListenerHandler = throttle(() => {
//如果是默认的window就直接拿window的滚动数据
    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
    }
  }, 100)
  
  onMounted(() => {
// 组件加载时判断有没有传过来一个实例
    if (elRef) el = elRef.value
    el.addEventListener("scroll", scrollListenerHandler)
  })
  
  onUnmounted(() => {
    el.removeEventListener("scroll", scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}

使用方法

const abc = ref()
//结构语法拿到返回的数据
//传入回调函数用法
 const {scrollTop} = useScroll(()=>{
})
// 传入实例对象用法
const {scrollTop} = useScroll(abc)
// 自己做判断
const showTab = computed(()=>{
  return scrollTop.value >=400
})
posted @   韩德才  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示