不建议监听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
})