useVirtualList

useVirtualList

::: warning より多くの機能を求めている場合は、代わりに vue-virtual-scroller を使用することを検討してください。 :::

簡単にバーチャルリストを作成します。バーチャルリスト(時にはバーチャルスクローラーと呼ばれる)は、多数のアイテムを効率的にレンダリングすることを可能にします。これらは、wrapper要素を使用してcontainer要素の全体の高さをエミュレートすることにより、必要最小限のDOMノードのみをレンダリングします。

使用法

シンプルなリスト

import { useVirtualList } from '@vueuse/core'

const { list, containerProps, wrapperProps } = useVirtualList(
  Array.from(Array.from({ length: 99999 }).keys()),
  {
    // `itemHeight`をアイテムの行と同期させてください。
    itemHeight: 22,
  },
)

設定

StateTypeDescription
itemHeightnumberwrapper要素の総高さが正しく計算されることを保証します。*
itemWidthnumberwrapper要素の総幅が正しく計算されることを保証します。*
overscannumber事前にレンダリングされるDOMノードの数。非常に速くスクロールした場合にアイテム間の空白を防ぎます。

* itemHeightまたはitemWidthは、レンダリングされる各行の高さと同期させる必要があります。リストの下部にスクロールしたときに余分な空白やちらつきが見られる場合は、itemHeightまたはitemWidthが行の高さと同じであることを確認してください。

リアクティブなリスト

import { useToggle, useVirtualList } from '@vueuse/core'
import { computed } from 'vue'

const [isEven, toggle] = useToggle()
const allItems = Array.from(Array.from({ length: 99999 }).keys())
const filteredList = computed(() => allItems.filter(i => isEven.value ? i % 2 === 0 : i % 2 === 1))

const { list, containerProps, wrapperProps } = useVirtualList(
  filteredList,
  {
    itemHeight: 22,
  },
)
<template>
  <p>現在表示中のアイテム: {{ isEven ? '偶数' : '奇数' }}</p>
  <button @click="toggle">
    偶数/奇数を切り替え
  </button>
  <div v-bind="containerProps" style="height: 300px">
    <div v-bind="wrapperProps">
      <div v-for="item in list" :key="item.index" style="height: 22px">
        Row: {{ item.data }}
      </div>
    </div>
  </div>
</template>

水平方向のリスト

import { useVirtualList } from '@vueuse/core'

const allItems = Array.from(Array.from({ length: 99999 }).keys())

const { list, containerProps, wrapperProps } = useVirtualList(
  allItems,
  {
    itemWidth: 200,
  },
)
<template>
  <div v-bind="containerProps" style="height: 300px">
    <div v-bind="wrapperProps">
      <div v-for="item in list" :key="item.index" style="width: 200px">
        Row: {{ item.data }}
      </div>
    </div>
  </div>
</template>

コンポーネントの使用法

<template>
  <UseVirtualList :list="list" :options="options" height="300px">
    <template #default="props">
      <!-- ここでリストの現在のアイテムを取得できます -->
      <div style="height: 22px">
        Row {{ props.index }} {{ props.data }}
      </div>
    </template>
  </UseVirtualList>
</template>

特定の要素にスクロールするには、コンポーネントはscrollTo(index: number) => voidを公開しています。