VirtualList 虚拟列表
只渲染可视区域内的列表项,用来展示成千上万条数据。滚动时渲染的节点数基本不变。
引入
import { HuiVirtualList } from '@nscode/handy-ui'
基础用法
items 传数据,item-size 传每一项的高度(px),height 设列表高度。默认插槽的 item 是 items 里的一项,index 是它的下标。下面是 1 万条订单:
<script setup lang="ts">
import { HuiVirtualList } from '@nscode/handy-ui'
const customers = ['张伟', '王芳', '李娜', '刘洋', '陈静', '杨磊']
const items = Array.from({ length: 10000 }, (_, i) => ({
id: i + 1,
orderNo: `SO${20260001 + i}`,
customer: customers[i % customers.length],
amount: ((i * 37) % 900) + 100
}))
</script>
<template>
<HuiVirtualList :items="items" :item-size="40" :height="400">
<template #default="{ item, index }">
<div class="row">
<span class="row__index">#{{ index + 1 }}</span>
<span class="row__main">{{ item.orderNo }} · {{ item.customer }}</span>
<span>¥ {{ item.amount }}.00</span>
</div>
</template>
</HuiVirtualList>
</template>
<style scoped>
.row {
display: flex;
align-items: center;
gap: 12px;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
.row__index {
width: 56px;
color: var(--hui-text-color-secondary);
}
.row__main {
flex: 1;
}
</style>
列表项本身只负责定位和高度,插槽内容要自己写内边距和分隔线;写 height: 100% 就能和行高一致。
不写插槽
不写插槽时直接显示每一项的内容(适合字符串、数字数组),带默认的内边距和分隔线。
<script setup lang="ts">
import { HuiVirtualList } from '@nscode/handy-ui'
const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安']
const items = Array.from({ length: 5000 }, (_, i) => `${cities[i % 8]}仓库 · 货架 ${i + 1}`)
</script>
<template>
<HuiVirtualList :items="items" :item-size="40" :height="240" />
</template>
函数高度
每一项高度不同时,item-size 传函数 (index, item) => number,返回这一项的高度。组件按返回值计算位置,不会自己测量 DOM。
下面是按部门分组的通讯录,部门标题行 32px,成员行 56px:
<script setup lang="ts">
import { HuiVirtualList } from '@nscode/handy-ui'
type Row = { type: 'group'; title: string } | { type: 'member'; name: string; phone: string }
const departments = ['研发部', '市场部', '财务部', '人事部', '销售部']
const surnames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴']
const givenNames = ['伟', '芳', '娜', '敏', '静', '磊', '洋', '勇', '军', '杰']
const items: Row[] = departments.flatMap((dept, d) => [
{ type: 'group' as const, title: `${dept}(200 人)` },
...Array.from({ length: 200 }, (_, i) => ({
type: 'member' as const,
name: `${surnames[(i + d) % 10]}${givenNames[Math.floor(i / 10) % 10]}`,
phone: `138 ${String(1000 + d * 200 + i).padStart(4, '0')} ${String(i * 7).padStart(4, '0')}`
}))
])
const getItemSize = (_index: number, item: Row) => (item.type === 'group' ? 32 : 56)
</script>
<template>
<HuiVirtualList :items="items" :item-size="getItemSize" :height="400">
<template #default="{ item }">
<div v-if="item.type === 'group'" class="group">{{ item.title }}</div>
<div v-else class="member">
<div>{{ item.name }}</div>
<div class="member__phone">{{ item.phone }}</div>
</div>
</template>
</HuiVirtualList>
</template>
<style scoped>
.group {
display: flex;
align-items: center;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
background-color: var(--hui-fill-color-light);
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
.member {
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
.member__phone {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
更新某一项的高度
内容渲染出来以后才知道高度时(例如展开详情),量好以后通过 ref 调用 updateItemHeight(index, height) 更新。只在 item-size 是函数时生效。下面点“展开”把这一行改成 112px,再点收起改回 48px:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiVirtualList } from '@nscode/handy-ui'
import type { VirtualListExpose } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => ({
id: i + 1,
title: `工单 WO-${String(i + 1).padStart(4, '0')}`,
detail: '客户反馈打印机无法连接,已远程排查网络配置,待上门更换网线。'
}))
const listRef = ref<VirtualListExpose | null>(null)
const expanded = ref(new Set<number>())
// 默认高度。展开后的高度由 updateItemHeight 单独记录
const getItemSize = () => 48
const toggle = (index: number) => {
const open = !expanded.value.has(index)
if (open) expanded.value.add(index)
else expanded.value.delete(index)
listRef.value?.updateItemHeight(index, open ? 112 : 48)
}
</script>
<template>
<HuiVirtualList ref="listRef" :items="items" :item-size="getItemSize" :height="320">
<template #default="{ item, index }">
<div class="ticket">
<div class="ticket__head">
<span>{{ item.title }}</span>
<HuiButton size="small" variant="text" type="primary" @click="toggle(index)">
{{ expanded.has(index) ? '收起' : '展开' }}
</HuiButton>
</div>
<p v-if="expanded.has(index)" class="ticket__detail">{{ item.detail }}</p>
</div>
</template>
</HuiVirtualList>
</template>
<style scoped>
.ticket {
box-sizing: border-box;
height: 100%;
padding: 8px 16px;
border-bottom: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color-lighter);
}
.ticket__head {
display: flex;
align-items: center;
justify-content: space-between;
height: 32px;
}
.ticket__detail {
margin: 8px 0 0;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
百分比高度
height 也可以写字符串,例如 '100%'、'30vh'。写百分比时父元素必须有确定的高度。列表会跟着容器尺寸变化重新计算可见项。
左边是 height="100%"(父元素高 240px),右边是 height="30vh"(窗口高度的 30%):
<script setup lang="ts">
import { HuiSpace, HuiVirtualList } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => `第 ${i + 1} 行`)
</script>
<template>
<HuiSpace fill align="start">
<div style="height: 240px">
<HuiVirtualList :items="items" :item-size="40" height="100%" />
</div>
<HuiVirtualList :items="items" :item-size="40" height="30vh" />
</HuiSpace>
</template>
滚动到指定项
通过 ref 调用 scrollTo(index),把第 index 项滚到列表顶部。下标超出范围时滚到开头或结尾。getScrollTop() 返回当前的滚动位置。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputNumber, HuiSpace, HuiVirtualList } from '@nscode/handy-ui'
import type { VirtualListExpose } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => `第 ${i + 1} 行`)
const listRef = ref<VirtualListExpose | null>(null)
const row = ref<number | undefined>(500)
const scrollTop = ref<number | null>(null)
// 第 n 行的下标是 n - 1
const go = (index: number) => {
listRef.value?.scrollTo(index)
}
const readScrollTop = () => {
scrollTop.value = listRef.value?.getScrollTop() ?? 0
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiInputNumber v-model="row" :min="1" :max="1000" />
<HuiButton type="primary" @click="go((row ?? 1) - 1)">滚动到第 {{ row ?? 1 }} 行</HuiButton>
<HuiButton @click="go(0)">第一行</HuiButton>
<HuiButton @click="go(999)">最后一行</HuiButton>
<HuiButton @click="go(99999)">超出范围(滚到结尾)</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<HuiButton variant="text" type="primary" @click="readScrollTop"
>读取 getScrollTop()</HuiButton
>
<span v-if="scrollTop !== null">当前滚动位置:{{ scrollTop }}px</span>
</HuiSpace>
<HuiVirtualList ref="listRef" :items="items" :item-size="40" :height="300" />
</HuiSpace>
</template>
监听滚动
scroll 事件的参数里有当前滚动位置 scrollTop,以及渲染出来的第一项的下标 startIndex 和最后一项的下一个下标 endIndex(不包含)。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiVirtualList } from '@nscode/handy-ui'
import type { VirtualListScrollEvent } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => `第 ${i + 1} 行`)
const info = ref('滚动列表看看')
const handleScroll = (event: VirtualListScrollEvent) => {
info.value = `scrollTop:${Math.round(event.scrollTop)}px,当前渲染下标 ${event.startIndex} ~ ${event.endIndex - 1}`
}
</script>
<template>
<p style="margin-bottom: 12px">{{ info }}</p>
<HuiVirtualList :items="items" :item-size="40" :height="300" @scroll="handleScroll" />
</template>
缓冲区
buffer 是可见区域上下各多渲染几项,默认 3。快速滚动时出现空白可以调大一些;调大以后每次渲染的节点也更多。
下面两个列表高 200px,一屏能看到 5 行。左边 buffer 是 0,右边是 10,滚动后看各自渲染了多少行:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiVirtualList } from '@nscode/handy-ui'
import type { VirtualListScrollEvent } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => `第 ${i + 1} 行`)
const countA = ref<number | null>(null)
const countB = ref<number | null>(null)
const onScrollA = (event: VirtualListScrollEvent) => {
countA.value = event.endIndex - event.startIndex
}
const onScrollB = (event: VirtualListScrollEvent) => {
countB.value = event.endIndex - event.startIndex
}
</script>
<template>
<HuiSpace fill align="start">
<div>
<p class="demo-label">buffer = 0:渲染了 {{ countA ?? '?' }} 行</p>
<HuiVirtualList
:items="items"
:item-size="40"
:height="200"
:buffer="0"
@scroll="onScrollA"
/>
</div>
<div>
<p class="demo-label">buffer = 10:渲染了 {{ countB ?? '?' }} 行</p>
<HuiVirtualList
:items="items"
:item-size="40"
:height="200"
:buffer="10"
@scroll="onScrollB"
/>
</div>
</HuiSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
稳定标识和像素滚动
itemKey 可以是字段名或函数,滚动方法会限制在有效范围内。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiVirtualList, HuiButton, HuiSpace } from '@nscode/handy-ui'
const list = ref<InstanceType<typeof HuiVirtualList>>()
const items = Array.from({ length: 100 }, (_, index) => ({ id: index, label: '条目 ' + index }))
const keyOf = (item: { id: number }) => item.id
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="list?.scrollToOffset(160)">滚动到 160px</HuiButton
><HuiButton @click="list?.scrollToBottom()">滚到底部</HuiButton></HuiSpace
>
<HuiVirtualList ref="list" :items="items" item-key="id" :item-size="32" :height="160"
><template #default="{ item }"
><div style="height: 32px">{{ item.label }}</div></template
></HuiVirtualList
>
<HuiVirtualList :items="items" :item-key="keyOf" :item-size="32" :height="96"
><template #default="{ item }"
><div style="height: 32px">函数 key:{{ item.label }}</div></template
></HuiVirtualList
>
</HuiSpace>
</template>
对齐、按 key 定位和确保可见
scrollTo(index, options) 支持 start、center、end、nearest,默认保持顶部对齐。ensureVisible(index) 使用 nearest:完整可见时保持位置,否则只滚动必要的距离;超过视口高度的行已经覆盖视口时也保持位置。
scrollToKey(key, options) 按当前数据的 itemKey 查找,找到返回 true,找不到返回 false 且不滚动。未设置 itemKey 时只接受数字下标;数字 0 与字符串 '0' 是不同的 key。测量过的行和重排后的数据共用当前高度及位置。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiVirtualList, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { VirtualListExpose } from '@nscode/handy-ui'
const list = ref<VirtualListExpose>()
const status = ref('选择一种定位方式')
const alignments = ['start', 'center', 'end', 'nearest'] as const
const items = Array.from({ length: 100 }, (_, index) => ({
id: index + 1000,
label: `条目 ${index + 1}`
}))
const locate = (key: number) => {
status.value = list.value?.scrollToKey(key, { align: 'center' })
? `已找到 key ${key}`
: `未找到 key ${key},保持位置`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-for="align in alignments" :key="align" @click="list?.scrollTo(20, { align })">
第 21 项:{{ align }}
</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<HuiButton @click="locate(1030)">按 key 1030 居中</HuiButton>
<HuiButton @click="locate(-1)">查找不存在的 key</HuiButton>
<HuiButton @click="list?.ensureVisible(20)">确保第 21 项可见</HuiButton>
<HuiButton @click="list?.scrollToKey(1080, { align: 'center', behavior: 'smooth' })">
平滑定位 key 1080
</HuiButton>
<HuiButton @click="list?.scrollToBottom('smooth')">平滑滚到底部</HuiButton>
</HuiSpace>
<span>{{ status }}</span>
<HuiVirtualList ref="list" :items="items" item-key="id" :item-size="32" :height="160">
<template #default="{ item }">
<div style="height: 100%">{{ item.label }} · key {{ item.id }}</div>
</template>
</HuiVirtualList>
</HuiSpace>
</template>
behavior: 'smooth' 交由浏览器滚动;getScrollTop() 和虚拟窗口跟随实际滚动位置,调用时不会立即变成终点。不支持原生平滑滚动的环境会即时定位。
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| items | T[] | - | 列表数据,必填 |
| itemSize | number | ((index: number, item: T) => number) | - | 每一项的高度(px),必填。传函数时按下标和数据返回每一项的高度 |
| height | number | string | 300 | 列表高度。数字按 px 处理;字符串原样使用,写百分比时父元素要有高度 |
| buffer | number | 3 | 可见区域上下各多渲染几项 |
| itemKey | string | ((item: T, index: number) => string | number) | - | 稳定的列表项标识,不传时使用下标 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| scroll | (event: VirtualListScrollEvent) | 列表滚动时触发,参数见下面的“类型”一节 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| default | { item: T; index: number } | 列表项内容。item 是 items 里的一项,index 是下标 |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| scrollTo | (index: number, options?: VirtualListScrollOptions) | void | 按下标定位;默认顶部对齐,超出范围时滚到开头或结尾 |
| scrollToKey | (key: string | number, options?: VirtualListScrollOptions) | boolean | 按当前 key 定位;未找到或卸载后返回 false |
| ensureVisible | (index: number, behavior?: ScrollBehavior) | void | 确保目标可见,使用 nearest 对齐 |
| getScrollTop | - | number | 获取当前滚动位置 |
| updateItemHeight | (index: number, height: number) | void | 更新某一项的实际高度,只在 itemSize 是函数时生效 |
| scrollToOffset | (offset: number, behavior?: ScrollBehavior) | void | 滚动到指定像素偏移,自动限制在有效范围 |
| scrollToBottom | (behavior?: ScrollBehavior) | void | 滚动到底部 |
类型
公开类型使用组件前缀。兼容映射:ItemSize → VirtualListItemSize。旧名仍可从 @nscode/handy-ui 导入,已标记 @deprecated,将在 1.0 删除。
import type {
VirtualListItemSize,
VirtualListProps,
VirtualListScrollEvent,
VirtualListScrollOptions,
VirtualListExpose
} from '@nscode/handy-ui'
type VirtualListItemSize<T = unknown> = number | ((index: number, item: T) => number)
interface VirtualListProps<T = unknown> {
/** 稳定的列表项标识,不传时使用下标 */
itemKey?: string | ((item: T, index: number) => string | number)
/** 列表数据 */
items: T[]
/** 列表项高度,数字或函数 */
itemSize: VirtualListItemSize<T>
/** 列表高度,数字按 px 处理;写百分比时父元素必须有确定的高度 */
height?: number | string
/** 可见区域上下各多渲染几项 */
buffer?: number
}
interface VirtualListScrollEvent {
/** 当前滚动位置 */
scrollTop: number
/** 渲染的第一项的下标 */
startIndex: number
/** 渲染的最后一项的下一个下标(不包含) */
endIndex: number
}
interface VirtualListScrollOptions {
align?: 'start' | 'center' | 'end' | 'nearest'
behavior?: ScrollBehavior
}
interface VirtualListExpose {
/** 滚动到指定偏移(px) */
scrollToOffset: (offset: number, behavior?: ScrollBehavior) => void
/** 滚动到底部 */
scrollToBottom: (behavior?: ScrollBehavior) => void
/** 滚动到指定下标的项 */
scrollTo: (index: number, options?: VirtualListScrollOptions) => void
scrollToKey: (key: string | number, options?: VirtualListScrollOptions) => boolean
ensureVisible: (index: number, behavior?: ScrollBehavior) => void
/** 获取当前滚动位置 */
getScrollTop: () => number
/** 更新某一项的实际高度(只在 itemSize 为函数时生效) */
updateItemHeight: (index: number, height: number) => void
}