Skip to content

useScroll

响应式滚动状态,检测滚动方向、是否到达边界。


函数签名

ts
function useScroll(
  element: MaybeRefOrGetter<HTMLElement | SVGElement | Window | Document | null | undefined>,
  options?: UseScrollOptions,
): {
  x: WritableComputedRef<number>
  y: WritableComputedRef<number>
  isScrolling: Ref<boolean>
  arrivedState: { left: boolean; right: boolean; top: boolean; bottom: boolean }
  directions: { left: boolean; right: boolean; top: boolean; bottom: boolean }
  measure(): void
}

基础用法

参数

参数说明类型默认值
element滚动目标元素(ref / getter / 原生元素)MaybeRefOrGetter<HTMLElement | Window | Document>
options配置项UseScrollOptions{}

UseScrollOptions

参数说明类型默认值
throttle滚动事件节流时间(ms),0 为禁用number0
idle滚动结束判定时间(ms)number200
offset边界到达判定的偏移量(px){ left?, right?, top?, bottom? }{ 0, 0, 0, 0 }
onScroll滚动时回调(e: Event) => void
onStop滚动停止回调(e: Event) => void
behavior设置 x/y 时的滚动行为MaybeRefOrGetter<'auto' | 'smooth'>'auto'
eventListenerOptions事件监听选项boolean | AddEventListenerOptions{ capture: false, passive: true }

返回值

属性说明类型
x水平滚动位置(可写,设置时触发 scrollTo)WritableComputedRef<number>
y垂直滚动位置(可写,设置时触发 scrollTo)WritableComputedRef<number>
isScrolling是否正在滚动Ref<boolean>
arrivedState是否到达各边界{ left, right, top, bottom }
directions滚动方向{ left, right, top, bottom }
measure手动重新计算状态() => void

代码示例

ts
import { ref } from 'vue'
import { useScroll } from 'ljf-hooks'

const el = ref<HTMLElement>()
const { x, y, isScrolling, arrivedState, directions } = useScroll(el, {
  behavior: 'smooth',
})

// 判断是否滚动到底部
const isBottom = computed(() => arrivedState.bottom)