Files
ks-app-employment-service/hook/useScrollDirection.js
2025-05-13 11:10:38 +08:00

49 lines
1.3 KiB
JavaScript

import {
ref
} from 'vue'
export function useScrollDirection(options = {}) {
const {
threshold = 200, // 滚动偏移阈值
throttleTime = 100, // 节流时间(毫秒)
onChange = null // 滚动方向变化的回调
} = options
const lastScrollTop = ref(0)
const accumulatedScroll = ref(0)
const isScrollingDown = ref(false)
let lastInvoke = 0
function handleScroll(e) {
const now = Date.now()
if (now - lastInvoke < throttleTime) return
lastInvoke = now
const scrollTop = e.detail.scrollTop
const delta = scrollTop - lastScrollTop.value
accumulatedScroll.value += delta
if (accumulatedScroll.value > threshold) {
if (!isScrollingDown.value) {
isScrollingDown.value = true
onChange?.(true) // 通知变更为向下
}
accumulatedScroll.value = 0
}
if (accumulatedScroll.value < -threshold) {
if (isScrollingDown.value) {
isScrollingDown.value = false
onChange?.(false) // 通知变更为向上
}
accumulatedScroll.value = 0
}
lastScrollTop.value = scrollTop
}
return {
isScrollingDown,
handleScroll
}
}