@neosjs/virtual-list
虚拟列表组件。只渲染可视区域附近的列表项,用内边距撑起总高度,支持定高/不定高项目、上下缓冲数量、触底事件与滚动定位,适合渲染万级数据量的长列表。
安装
sh
pnpm add @neosjs/virtual-listsh
npm i @neosjs/virtual-listsh
yarn add @neosjs/virtual-list快速上手
data 传入列表数据,通过 item 插槽渲染每一项;height 指定可视区域高度。
vue
<script setup lang="ts">
import { VirtualList } from '@neosjs/virtual-list'
import { ref } from 'vue'
const data = ref(
Array.from({ length: 10000 }, (_, i) => ({ key: i, label: `第 ${i + 1} 项` }))
)
</script>
<template>
<VirtualList :data="data" item-key="key" :height="300">
<template #item="{ item }">
<div class="list-item">
{{ item.label }}
</div>
</template>
</VirtualList>
</template>触底加载
滚动到底部时触发 reachBottom 事件,可配合分页请求实现无限滚动。
vue
<VirtualList :data="data" :height="300" @reach-bottom="loadMore">
<template #item="{ item, index }">
<div>{{ index }} - {{ item.label }}</div>
</template>
</VirtualList>定高与不定高
- 项目高度固定时设置
fixed-size,性能更好。 - 项目高度不定时,默认按
estimated-size预估高度,实际渲染后再根据真实尺寸修正(无需额外配置)。
Props
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| height | number | string | 200 | 可视区域高度 |
| data | Array | [] | 列表数据 |
| threshold | number | 0 | 开启虚拟滚动的数量阈值,数据量不大于该值时直接全量渲染 |
| item-key | string | 'key' | 数据项的唯一键字段名 |
| fixed-size | boolean | false | 项目高度是否固定 |
| estimated-size | number | 30 | 不定高时每项的预估高度(px) |
| buffer | number | 10 | 视口边界外提前挂载的项数量 |
| component | string | object | 'div' | 容器渲染的标签或组件,传对象可分别配置 container / list / content |
| list-attrs | object | — | 列表层元素附加的属性 |
| content-attrs | object | — | 内容层元素附加的属性 |
| padding-position | string | 'content' | 撑高内边距应用的层,'content' 或 'list' |
Emits
| 事件名 | 参数 | 说明 |
|---|---|---|
| scroll | (ev: Event) | 滚动时触发 |
| reachBottom | (ev: Event) | 滚动到底部时触发 |
Slots
| 插槽名 | 参数 | 说明 |
|---|---|---|
| item | item: 数据项, index: number | 列表项内容,index 为在完整数据中的索引 |
方法
通过 ref 可调用以下方法:
| 方法名 | 参数 | 说明 |
|---|---|---|
| scrollTo | (options: number | { index?: number, key?: VirtualItemKey, align?: 'auto' | 'top' | 'bottom' }) | 滚动到指定像素位置,或滚动到指定索引 / key 的列表项 |