跳到主要內容

useScroll

類別
匯出大小
1.79 kB
上次變更
5 天前

響應式的滾動位置和狀態。

示範

左上
左下
右上
右下
滾動我
X 軸位置
Y 軸位置
isScrollingfalse
到達頂部
true
到達右側
false
到達底部
false
到達左側
true
向上滾動
false
向右滾動
false
向下滾動
false
向左滾動
false

用法

vue
<script setup lang="ts">
import { useScroll } from '@vueuse/core'
import { useTemplateRef } from 'vue'

const el = useTemplateRef<HTMLElement>('el')
const { x, y, isScrolling, arrivedState, directions } = useScroll(el)
</script>

<template>
  <div ref="el" />
</template>

使用偏移量

js
const { x, y, isScrolling, arrivedState, directions } = useScroll(el, {
  offset: { top: 30, bottom: 30, right: 30, left: 30 },
})

設定滾動位置

設定 x 和 y 值以使元素滾動到該位置。

vue
<script setup lang="ts">
import { useScroll } from '@vueuse/core'
import { useTemplateRef } from 'vue'

const el = useTemplateRef<HTMLElement>('el')
const { x, y } = useScroll(el)
</script>

<template>
  <div ref="el" />
  <button @click="x += 10">
    Scroll right 10px
  </button>
  <button @click="y += 10">
    Scroll down 10px
  </button>
</template>

平滑滾動

設定 `behavior: smooth` 以啟用平滑滾動。`behavior` 選項預設為 `auto`,表示不使用平滑滾動。有關更多資訊,請參閱 `window.scrollTo()` 上的 `behavior` 選項。

ts
import { useScroll } from '@vueuse/core'
import { useTemplateRef } from 'vue'

const el = useTemplateRef<HTMLElement>('el')
const { x, y } = useScroll(el, { behavior: 'smooth' })

// Or as a `ref`:
const smooth = ref(false)
const behavior = computed(() => smooth.value ? 'smooth' : 'auto')
const { x, y } = useScroll(el, { behavior })
js
import { useScroll } from '@vueuse/core'
import { useTemplateRef } from 'vue'
const el = useTemplateRef('el')
const { x, y } = useScroll(el, { behavior: 'smooth' })
// Or as a `ref`:
const smooth = ref(false)
const behavior = computed(() => (smooth.value ? 'smooth' : 'auto'))
const { x, y } = useScroll(el, { behavior })

指令用法

此函式也透過 `@vueuse/components` 套件提供指令版本。 深入瞭解用法

vue
<script setup lang="ts">
import type { UseScrollReturn } from '@vueuse/core'
import { vScroll } from '@vueuse/components'

const data = ref([1, 2, 3, 4, 5, 6])

function onScroll(state: UseScrollReturn) {
  console.log(state) // {x, y, isScrolling, arrivedState, directions}
}
</script>

<template>
  <div v-scroll="onScroll">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>

  <!-- with options -->
  <div v-scroll="[onScroll, { throttle: 10 }]">
    <div v-for="item in data" :key="item">
      {{ item }}
    </div>
  </div>
</template>

類型宣告

顯示類型宣告
typescript
export interface UseScrollOptions extends ConfigurableWindow {
  /**
   * Throttle time for scroll event, it’s disabled by default.
   *
   * @default 0
   */
  throttle?: number
  /**
   * The check time when scrolling ends.
   * This configuration will be setting to (throttle + idle) when the `throttle` is configured.
   *
   * @default 200
   */
  idle?: number
  /**
   * Offset arrived states by x pixels
   *
   */
  offset?: {
    left?: number
    right?: number
    top?: number
    bottom?: number
  }
  /**
   * Trigger it when scrolling.
   *
   */
  onScroll?: (e: Event) => void
  /**
   * Trigger it when scrolling ends.
   *
   */
  onStop?: (e: Event) => void
  /**
   * Listener options for scroll event.
   *
   * @default {capture: false, passive: true}
   */
  eventListenerOptions?: boolean | AddEventListenerOptions
  /**
   * Optionally specify a scroll behavior of `auto` (default, not smooth scrolling) or
   * `smooth` (for smooth scrolling) which takes effect when changing the `x` or `y` refs.
   *
   * @default 'auto'
   */
  behavior?: MaybeRefOrGetter<ScrollBehavior>
  /**
   * On error callback
   *
   * Default log error to `console.error`
   */
  onError?: (error: unknown) => void
}
/**
 * Reactive scroll.
 *
 * @see https://vueuse.dev.org.tw/useScroll
 * @param element
 * @param options
 */
export declare function useScroll(
  element: MaybeRefOrGetter<
    HTMLElement | SVGElement | Window | Document | null | undefined
  >,
  options?: UseScrollOptions,
): {
  x: WritableComputedRef<number, number>
  y: WritableComputedRef<number, number>
  isScrolling: ShallowRef<boolean, boolean>
  arrivedState: {
    left: boolean
    right: boolean
    top: boolean
    bottom: boolean
  }
  directions: {
    left: boolean
    right: boolean
    top: boolean
    bottom: boolean
  }
  measure(): void
}
export type UseScrollReturn = ReturnType<typeof useScroll>

原始碼

原始碼示範文件

貢獻者

Anthony Fu
Anthony Fu
IlyaL
webfansplz
kongmoumou
Curt Grimes
Robin
719media
Dima Kaltovich
Poet
Nico Prat
MinatoHikari
Vladimir
AlanYu
Scott Bedard
Christian Martinez
丶远方
holtergram
Ayaka Rizumu
云游君
btea
Thierry Michel
Pavel Yankovski
Bobakanoosh
Joseph Fitz Hughes

變更日誌

v12.8.0 on 3/5/2025
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
4b7ab - fix: handle negative scroll values (#4613)
v12.3.0 on 1/2/2025
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
a033e - feat(useWindowScroll): use useScroll under the hood (#4424)
v12.1.0 on 12/22/2024
90ff4 - fix: to properly report arriveState for elastic scroll (#4133)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.10.0 on 5/27/2024
317ca - fix: sync scroll val to internal state, fix #3809 (#3817)
v10.8.0 on 2/20/2024
fab86 - fix: add onError hook and avoid throws by default, fix #3580 (#3605)
v10.6.1 on 11/13/2023
e9742 - fix: can not read properties of null (reading document) (#3544)
v10.6.0 on 11/9/2023
86bd8 - fix: trigger once onMounted to get correct inital arrivedStates values (#3384)
v10.4.0 on 8/25/2023
c1b29 - fix: evade edge case when window or document is Proxy (#3280)
v10.3.0 on 7/30/2023
dde41 - fix: support configurable window (#3229)
v10.2.0 on 6/16/2023
8855f - fix: support window in setArrivedState (#3086)
v10.1.1 on 5/1/2023
a88fe - fix(useInfiniteScroll): re-measure arrived states when async infinite scroll resolves (#3030)
v10.0.0-beta.4 on 4/13/2023
23b9a - fix: add support for row-reverse and column-reverse (#2577)
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.13.0 on 2/18/2023
f8872 - feat: support scrollend event (#2716)

以 MIT 授權條款發布。