主题
useVirtualList
WARNING
如果你希望获得更多功能,考虑使用 @tanstack/vue-virtual 替代。
轻松创建虚拟列表。虚拟列表(有时称为 虚拟滚动器)允许你高效地渲染大量项目。它们仅渲染显示 container 元素内项目所需的最少 DOM 节点,通过使用 wrapper 元素模拟容器元素的完整高度。
🌐 Create virtual lists with ease. Virtual lists (sometimes called virtual scrollers) allow you to render a large number of items performantly. They only render the minimum number of DOM nodes necessary to show the items within the container element by using the wrapper element to emulate the container element's full height.
示例
用法
🌐 Usage
简单清单
🌐 Simple list
ts
import { useVirtualList } from '@vueuse/core'
const { list, containerProps, wrapperProps } = useVirtualList(
Array.from(Array.from({ length: 99999 }).keys()),
{
// Keep `itemHeight` in sync with the item's row.
itemHeight: 22,
},
)配置
🌐 Config
| 状态 | 类型 | 描述 |
|---|---|---|
| itemHeight | “number” | 确保“wrapper”元素的总高度计算正确。* |
| itemWidth | 'number' | 确保“wrapper”元素的总宽度计算正确。* |
| 过扫描 | “number” | 预渲染DOM节点数量。如果你滚动得很快,可以防止物品之间的空白。 |
itemHeight或itemWidth必须与渲染的每一行的高度保持同步。如果在滚动到列表底部时看到额外的空白或抖动,请确保itemHeight或itemWidth与行的高度相同。
反应式列表
🌐 Reactive list
ts
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,
},
)vue
<template>
<p>Showing {{ isEven ? 'even' : 'odd' }} items</p>
<button @click="toggle">
Toggle Even/Odd
</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>横向列表
🌐 Horizontal list
ts
import { useVirtualList } from '@vueuse/core'
const allItems = Array.from(Array.from({ length: 99999 }).keys())
const { list, containerProps, wrapperProps } = useVirtualList(
allItems,
{
itemWidth: 200,
},
)vue
<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>组件用法
🌐 Component Usage
vue
<template>
<UseVirtualList :list="list" :options="options" height="300px">
<template #default="props">
<!-- you can get current item of list here -->
<div style="height: 22px">
Row {{ props.index }} {{ props.data }}
</div>
</template>
</UseVirtualList>
</template>要滚动到特定元素,组件提供了 scrollTo(index: number) => void。
🌐 To scroll to a specific element, the component exposes scrollTo(index: number) => void.