VirtualList 虚拟列表
只渲染可视区域内的列表项,用来展示成千上万条数据。滚动时渲染的节点数基本不变。
引入
import { NsVirtualList } from '@ns/ui'
基础用法
items 传数据,item-size 传每一项的高度(px),height 设列表高度。默认插槽的 item 是 items 里的一项,index 是它的下标。下面是 1 万条订单:
<script setup lang="ts">
import { NsVirtualList } from '@ns/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>
<NsVirtualList :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>
</NsVirtualList>
</template>
<style scoped>
.row {
display: flex;
align-items: center;
gap: 12px;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
border-bottom: var(--ns-border-width) var(--ns-border-style) var(--ns-border-color-lighter);
}
.row__index {
width: 56px;
color: var(--ns-text-color-secondary);
}
.row__main {
flex: 1;
}
</style>
列表项本身只负责定位和高度,插槽内容要自己写内边距和分隔线;写 height: 100% 就能和行高一致。
不写插槽
不写插槽时直接显示每一项的内容(适合字符串、数字数组),带默认的内边距和分隔线。
<script setup lang="ts">
import { NsVirtualList } from '@ns/ui'
const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安']
const items = Array.from({ length: 5000 }, (_, i) => `${cities[i % 8]}仓库 · 货架 ${i + 1}`)
</script>
<template>
<NsVirtualList :items="items" :item-size="40" :height="240" />
</template>
函数高度
每一项高度不同时,item-size 传函数 (index, item) => number,返回这一项的高度。组件按返回值计算位置,不会自己测量 DOM。
下面是按部门分组的通讯录,部门标题行 32px,成员行 56px:
<script setup lang="ts">
import { NsVirtualList } from '@ns/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>
<NsVirtualList :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>
</NsVirtualList>
</template>
<style scoped>
.group {
display: flex;
align-items: center;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
background-color: var(--ns-fill-color-light);
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
.member {
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
height: 100%;
padding: 0 16px;
border-bottom: var(--ns-border-width) var(--ns-border-style) var(--ns-border-color-lighter);
}
.member__phone {
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
更新某一项的高度
内容渲染出来以后才知道高度时(例如展开详情),量好以后通过 ref 调用 updateItemHeight(index, height) 更新。只在 item-size 是函数时生效。下面点“展开”把这一行改成 112px,再点收起改回 48px:
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsVirtualList } from '@ns/ui'
import type { VirtualListExpose } from '@ns/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>
<NsVirtualList ref="listRef" :items="items" :item-size="getItemSize" :height="320">
<template #default="{ item, index }">
<div class="ticket">
<div class="ticket__head">
<span>{{ item.title }}</span>
<NsButton size="small" variant="text" type="primary" @click="toggle(index)">
{{ expanded.has(index) ? '收起' : '展开' }}
</NsButton>
</div>
<p v-if="expanded.has(index)" class="ticket__detail">{{ item.detail }}</p>
</div>
</template>
</NsVirtualList>
</template>
<style scoped>
.ticket {
box-sizing: border-box;
height: 100%;
padding: 8px 16px;
border-bottom: var(--ns-border-width) var(--ns-border-style) var(--ns-border-color-lighter);
}
.ticket__head {
display: flex;
align-items: center;
justify-content: space-between;
height: 32px;
}
.ticket__detail {
margin: 8px 0 0;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
百分比高度
height 也可以写字符串,例如 '100%'、'30vh'。写百分比时父元素必须有确定的高度。列表会跟着容器尺寸变化重新计算可见项。
左边是 height="100%"(父元素高 240px),右边是 height="30vh"(窗口高度的 30%):
<script setup lang="ts">
import { NsSpace, NsVirtualList } from '@ns/ui'
const items = Array.from({ length: 1000 }, (_, i) => `第 ${i + 1} 行`)
</script>
<template>
<NsSpace fill align="start">
<div style="height: 240px">
<NsVirtualList :items="items" :item-size="40" height="100%" />
</div>
<NsVirtualList :items="items" :item-size="40" height="30vh" />
</NsSpace>
</template>
滚动到指定项
通过 ref 调用 scrollTo(index),把第 index 项滚到列表顶部。下标超出范围时滚到开头或结尾。getScrollTop() 返回当前的滚动位置。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsInputNumber, NsSpace, NsVirtualList } from '@ns/ui'
import type { VirtualListExpose } from '@ns/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>
<NsSpace direction="vertical" fill>
<NsSpace wrap>
<NsInputNumber v-model="row" :min="1" :max="1000" />
<NsButton type="primary" @click="go((row ?? 1) - 1)">滚动到第 {{ row ?? 1 }} 行</NsButton>
<NsButton @click="go(0)">第一行</NsButton>
<NsButton @click="go(999)">最后一行</NsButton>
<NsButton @click="go(99999)">超出范围(滚到结尾)</NsButton>
</NsSpace>
<NsSpace wrap>
<NsButton variant="text" type="primary" @click="readScrollTop">读取 getScrollTop()</NsButton>
<span v-if="scrollTop !== null">当前滚动位置:{{ scrollTop }}px</span>
</NsSpace>
<NsVirtualList ref="listRef" :items="items" :item-size="40" :height="300" />
</NsSpace>
</template>
监听滚动
scroll 事件的参数里有当前滚动位置 scrollTop,以及渲染出来的第一项的下标 startIndex 和最后一项的下一个下标 endIndex(不包含)。
<script setup lang="ts">
import { ref } from 'vue'
import { NsVirtualList } from '@ns/ui'
import type { VirtualListScrollEvent } from '@ns/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>
<NsVirtualList :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 { NsSpace, NsVirtualList } from '@ns/ui'
import type { VirtualListScrollEvent } from '@ns/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>
<NsSpace fill align="start">
<div>
<p class="demo-label">buffer = 0:渲染了 {{ countA ?? '?' }} 行</p>
<NsVirtualList :items="items" :item-size="40" :height="200" :buffer="0" @scroll="onScrollA" />
</div>
<div>
<p class="demo-label">buffer = 10:渲染了 {{ countB ?? '?' }} 行</p>
<NsVirtualList
:items="items"
:item-size="40"
:height="200"
:buffer="10"
@scroll="onScrollB"
/>
</div>
</NsSpace>
</template>
<style scoped>
.demo-label {
margin: 0 0 8px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| items | T[] | - | 列表数据,必填 |
| itemSize | number | ((index: number, item: T) => number) | - | 每一项的高度(px),必填。传函数时按下标和数据返回每一项的高度 |
| height | number | string | 300 | 列表高度。数字按 px 处理;字符串原样使用,写百分比时父元素要有高度 |
| buffer | number | 3 | 可见区域上下各多渲染几项 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| scroll | (event: VirtualListScrollEvent) | 列表滚动时触发,参数见下面的“类型”一节 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| default | { item: T; index: number } | 列表项内容。item 是 items 里的一项,index 是下标 |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| scrollTo | (index: number) | void | 把第 index 项滚到列表顶部,超出范围时滚到开头或结尾 |
| getScrollTop | - | number | 获取当前滚动位置 |
| updateItemHeight | (index: number, height: number) | void | 更新某一项的实际高度,只在 itemSize 是函数时生效 |
类型
import type { ItemSize, VirtualListProps, VirtualListScrollEvent, VirtualListExpose } from '@ns/ui'
type ItemSize<T = unknown> = number | ((index: number, item: T) => number)
interface VirtualListProps<T = unknown> {
items: T[]
itemSize: ItemSize<T>
height?: number | string
buffer?: number
}
interface VirtualListScrollEvent {
/** 当前滚动位置 */
scrollTop: number
/** 渲染的第一项的下标 */
startIndex: number
/** 渲染的最后一项的下一个下标(不包含) */
endIndex: number
}
interface VirtualListExpose {
scrollTo: (index: number) => void
getScrollTop: () => number
updateItemHeight: (index: number, height: number) => void
}
注意事项
height写百分比时,父元素必须有确定的高度,否则列表会被内容撑开,虚拟滚动失效。- 函数形式的
itemSize必须返回准确的高度。组件不会自动测量列表项,高度和实际内容不一致时会出现重叠或空隙;内容高度要渲染后才知道时,量好以后用updateItemHeight更新。返回 0 或负数时按 0 处理。 - 列表项的 key 用的是下标。在头部插入或删除数据时,行内组件的状态(输入框内容、展开状态等)会错到别的行,这类场景要把状态放在数据里。
items只做浅监听:替换数组或改变长度时会重新计算;直接改某一项的字段不会重新计算高度,需要时替换整个数组。- 数据变少或清空后,滚动位置会自动夹到新的最大值,不会停在空白区域。
- 列表项是绝对定位的一层里按顺序排列的
div,自定义样式时用.ns-virtual-list__item选择列表项,不要依赖它是.ns-virtual-list__wrapper的直接子元素。 - 只支持纵向滚动。
优化点
- [ ] 支持
itemKey,用数据里的字段作为列表项的 key - [ ] 支持列表项高度自动测量
- [ ] 增加
scrollToOffset、scrollToBottom方法 - [ ] 支持横向虚拟滚动、网格虚拟滚动
- [ ] 补充列表的无障碍属性(
role="list"、aria-setsize等)