Appearance
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 为禁用 | number | 0 |
| idle | 滚动结束判定时间(ms) | number | 200 |
| 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)