Files
cz-web/src/composables/useScroll.ts
2026-10-01 17:24:57 +08:00

26 lines
815 B
TypeScript

import { computed, onMounted, onUnmounted, ref, type ComputedRef, type Ref } from 'vue'
export function useScroll(threshold = 200): {
scrollY: Ref<number>
isAtTop: ComputedRef<boolean>
showBackTop: ComputedRef<boolean>
scrollToTop: (smooth?: boolean) => void
} {
const scrollY = ref(0)
const isAtTop = computed(() => scrollY.value <= 0)
const showBackTop = computed(() => scrollY.value > threshold)
function onScroll(): void {
scrollY.value = window.scrollY
}
function scrollToTop(smooth = true): void {
window.scrollTo({ top: 0, behavior: smooth ? 'smooth' : 'auto' })
}
onMounted(() => window.addEventListener('scroll', onScroll, { passive: true }))
onUnmounted(() => window.removeEventListener('scroll', onScroll))
return { scrollY, isAtTop, showBackTop, scrollToTop }
}