コンテンツにスキップ

useScroll

カテゴリ
エクスポートサイズ
1.53 kB
最終変更
先週

スクロール位置と状態をリアクティブに。

デモ

左上
左下
右上
右下
スクロールしてください
X位置
Y位置
isScrollingfalse
上端に到達
true
右端に到達
false
下端に到達
false
左端に到達
true
上方向にスクロール中
false
右方向にスクロール中
false
下方向にスクロール中
false
左方向にスクロール中
false

使用法

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

const el = ref<HTMLElement | null>(null)
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'

const el = ref<HTMLElement | null>(null)
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'

const el = ref<HTMLElement | null>(null)
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'
const el = ref(null)
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.dokyumento.jp/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: Ref<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
webfansplz
Anthony Fu
kongmoumou
Curt Grimes
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.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化し、クリーンアップ (#4349)
v10.10.0 2024/05/27
317ca - fix: スクロール値を内部状態に同期、#3809を修正 (#3817)
v10.8.0 2024/02/20
fab86 - fix: onErrorフックを追加し、デフォルトでスローを回避、#3580を修正 (#3605)
v10.6.1 2023/11/13
e9742 - fix: null のプロパティ (document を読み込み中) を読み取ることができない (#3544)
v10.6.0 2023/11/09
86bd8 - fix: 正しい初期 arrivedStates 値を取得するために、onMounted を一度トリガー (#3384)
v10.4.0 2023/08/25
c1b29 - fix: window または document が Proxy である場合のエッジケースを回避 (#3280)
v10.3.0 2023/07/30
dde41 - fix: 設定可能な window をサポート (#3229)
v10.2.0 2023/06/16
8855f - fix: setArrivedState で window をサポート (#3086)
v10.1.1 2023/05/01
a88fe - fix(useInfiniteScroll): 非同期の無限スクロールが解決されたときに、到達状態を再測定 (#3030)
v10.0.0-beta.4 2023/04/13
23b9a - fix: row-reverse および column-reverse のサポートを追加 (#2577)
4d757 - feat(types)!: MaybeComputedRefMaybeRefOrGetter にリネーム
0a72b - feat(toValue): resolveUnreftoValue にリネーム
v9.13.0 2023/02/18
f8872 - feat: scrollend イベントをサポート (#2716)
v9.5.0 2022/11/09
9cd92 - fix: スロットルパラメータを設定した後、期待される結果が返されない (#2390)
v9.3.0 2022/09/26
324ff - feat: スクロール位置の設定とスムーズスクロールの切り替えをサポート (#1996)

MITライセンスの下でリリースされています。