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
}