VirtualList
Render only visible list items to display thousands of records while keeping the number of rendered nodes roughly constant during scrolling.
Import
import { HuiVirtualList } from '@nscode/handy-ui'
Basic usage
Pass data through items, each item's height in pixels through item-size, and the list height through height. The default slot receives item and its index in items. This example contains 10,000 orders:
<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>
The item wrapper provides positioning and height only. Add padding and separators to your slot content. Use height: 100% to fill the row.
Without a slot
When no slot is provided, each item is displayed directly with default padding and separators. This works well for arrays of strings or numbers.
<script setup lang="ts">
import { HuiVirtualList } from '@nscode/handy-ui'
const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安']
const items = Array.from(
{ length: 5000 },
(_, i) => `${cities[i % 8]} warehouse · Shelf ${i + 1}`
)
</script>
<template>
<HuiVirtualList :items="items" :item-size="40" :height="240" />
</template>
Height functions
For varying heights, pass (index, item) => number to item-size. The component calculates positions from the returned heights; it does not measure the DOM automatically.
This example groups contacts by department, with 32px department rows and 56px member rows:
<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 people)` },
...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>
Updating an item height
When height is known only after rendering, such as after expanding details, measure it and call updateItemHeight(index, height) through a ref. This works only when item-size is a function. Click Expand to change a row to 112px, then Collapse to return it to 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: `Work order WO-${String(i + 1).padStart(4, '0')}`,
detail:
'The customer reported a disconnected printer. Network settings were checked remotely; an on-site cable replacement is pending.'
}))
const listRef = ref<VirtualListExpose | null>(null)
const expanded = ref(new Set<number>())
// Default height. Expanded heights are recorded separately with 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) ? 'Collapse' : 'Expand' }}
</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>
Percentage heights
height also accepts strings such as '100%' or '30vh'. Percentage heights require a parent with a definite height. The list recalculates visible items when its container resizes.
The left list uses height="100%" inside a 240px-high parent. The right uses height="30vh", or 30% of the viewport height:
<script setup lang="ts">
import { HuiSpace, HuiVirtualList } from '@nscode/handy-ui'
const items = Array.from({ length: 1000 }, (_, i) => `Row ${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>
Scrolling to an item
Call scrollTo(index) through a ref to place an item at the top. Out-of-range indices are clamped to the beginning or end. getScrollTop() returns the current scroll position.
<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) => `Row ${i + 1}`)
const listRef = ref<VirtualListExpose | null>(null)
const row = ref<number | undefined>(500)
const scrollTop = ref<number | null>(null)
// Row n has index 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)"
>Scroll to row {{ row ?? 1 }} now</HuiButton
>
<HuiButton @click="go(0)">First row</HuiButton>
<HuiButton @click="go(999)">Last row</HuiButton>
<HuiButton @click="go(99999)">Out of range (scroll to end)</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<HuiButton variant="text" type="primary" @click="readScrollTop"
>Read getScrollTop()</HuiButton
>
<span v-if="scrollTop !== null">Current scroll position: {{ scrollTop }}px</span>
</HuiSpace>
<HuiVirtualList ref="listRef" :items="items" :item-size="40" :height="300" />
</HuiSpace>
</template>
Scroll events
The scroll event provides the current scrollTop, the first rendered index startIndex, and the exclusive index after the last rendered item, 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) => `Row ${i + 1}`)
const info = ref('Scroll the list')
const handleScroll = (event: VirtualListScrollEvent) => {
info.value = `scrollTop:${Math.round(event.scrollTop)}px, rendered indices ${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
buffer sets the extra items rendered above and below the visible range, defaulting to 3. Increase it if fast scrolling reveals blank areas; larger values also render more nodes.
Each list below is 200px high and shows five rows. The left uses buffer 0 and the right 10. Scroll to compare the number of rendered rows:
<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) => `Row ${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 ?? '?' }} rows rendered</p>
<HuiVirtualList
:items="items"
:item-size="40"
:height="200"
:buffer="0"
@scroll="onScrollA"
/>
</div>
<div>
<p class="demo-label">buffer = 10: {{ countB ?? '?' }} rows rendered</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>
Stable keys and pixel scrolling
itemKey accepts a field name or function. Scrolling methods clamp their targets to the valid range.
<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: 'Item ' + index }))
const keyOf = (item: { id: number }) => item.id
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="list?.scrollToOffset(160)">Scroll to 160px</HuiButton
><HuiButton @click="list?.scrollToBottom()">Scroll to bottom</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">Function key: {{ item.label }}</div></template
></HuiVirtualList
>
</HuiSpace>
</template>
Alignment, key lookup, and visibility
scrollTo(index, options) supports start, center, end, and nearest, with top alignment by default. ensureVisible(index) uses nearest: a fully visible item keeps its position; otherwise, the list scrolls only as far as needed. A row taller than the viewport also stays in place when it already covers the viewport.
scrollToKey(key, options) looks up itemKey in the current data. It returns true when found, or false without scrolling when missing. Without itemKey, it accepts only numeric indices; the number 0 and string '0' are different keys. Measured rows and reordered data use their current heights and positions.
<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('Choose a navigation method')
const alignments = ['start', 'center', 'end', 'nearest'] as const
const items = Array.from({ length: 100 }, (_, index) => ({
id: index + 1000,
label: `Item ${index + 1}`
}))
const locate = (key: number) => {
status.value = list.value?.scrollToKey(key, { align: 'center' })
? `Found key ${key}`
: `Missing key ${key}; position unchanged`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-for="align in alignments" :key="align" @click="list?.scrollTo(20, { align })">
Item 21:{{ align }}
</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<HuiButton @click="locate(1030)">Center key 1030</HuiButton>
<HuiButton @click="locate(-1)">Find a missing key</HuiButton>
<HuiButton @click="list?.ensureVisible(20)">Ensure item 21 is visible</HuiButton>
<HuiButton @click="list?.scrollToKey(1080, { align: 'center', behavior: 'smooth' })">
Scroll smoothly to key 1080
</HuiButton>
<HuiButton @click="list?.scrollToBottom('smooth')">Scroll smoothly to the bottom</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' delegates scrolling to the browser. getScrollTop() and the rendered window follow the actual scroll position instead of jumping immediately to the destination. Environments without the native scrolling method fall back to immediate navigation.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| items | T[] | - | Required list data |
| itemSize | number | ((index: number, item: T) => number) | - | Required row height in pixels; a function returns each row's height from its index and data |
| height | number | string | 300 | List height; numbers are pixels and strings are used as provided. Percentage heights require a parent height |
| buffer | number | 3 | Extra items rendered above and below the visible range |
| itemKey | string | ((item: T, index: number) => string | number) | - | Stable item key; defaults to the array index |
Events
| Event | Parameters | Description |
|---|---|---|
| scroll | (event: VirtualListScrollEvent) | Emitted when the list scrolls; see Types for the payload |
Slots
| Slot | Scope | Description |
|---|---|---|
| default | { item: T; index: number } | Item content; item is the entry in items, and index is its index |
Methods
Call through the component ref.
| Method | Parameters | Return value | Description |
|---|---|---|---|
| scrollTo | (index: number, options?: VirtualListScrollOptions) | void | Navigate to an index; top alignment by default, clamping out-of-range indices to the beginning or end. |
| scrollToKey | (key: string | number, options?: VirtualListScrollOptions) | boolean | Navigate by the current key; return false when missing or unmounted. |
| ensureVisible | (index: number, behavior?: ScrollBehavior) | void | Ensure visibility using nearest alignment. |
| getScrollTop | - | number | Read the current scroll position |
| updateItemHeight | (index: number, height: number) | void | Update a measured row height; only applies when itemSize is a function |
| scrollToOffset | (offset: number, behavior?: ScrollBehavior) | void | Scroll to a pixel offset, clamped to the valid range. |
| scrollToBottom | (behavior?: ScrollBehavior) | void | Scroll to the bottom. |
Types
Public types use a component prefix. Compatibility mapping: ItemSize → VirtualListItemSize. The old name remains importable from @nscode/handy-ui, is marked @deprecated, and will be removed in 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> {
/** Stable item key; defaults to the index */
itemKey?: string | ((item: T, index: number) => string | number)
/** List data */
items: T[]
/** Item height, as a number or function */
itemSize: VirtualListItemSize<T>
/** List height; numbers are pixels and percentages require a parent with a definite height */
height?: number | string
/** Extra items rendered above and below the visible area */
buffer?: number
}
interface VirtualListScrollEvent {
/** Current scroll position */
scrollTop: number
/** First rendered index */
startIndex: number
/** Exclusive index after the last rendered item */
endIndex: number
}
interface VirtualListScrollOptions {
align?: 'start' | 'center' | 'end' | 'nearest'
behavior?: ScrollBehavior
}
interface VirtualListExpose {
/** Scroll to an offset in pixels */
scrollToOffset: (offset: number, behavior?: ScrollBehavior) => void
/** Scroll to the bottom */
scrollToBottom: (behavior?: ScrollBehavior) => void
/** Scroll to an item index */
scrollTo: (index: number, options?: VirtualListScrollOptions) => void
scrollToKey: (key: string | number, options?: VirtualListScrollOptions) => boolean
ensureVisible: (index: number, behavior?: ScrollBehavior) => void
/** Get the current scroll position */
getScrollTop: () => number
/** Update a measured row height (only when itemSize is a function) */
updateItemHeight: (index: number, height: number) => void
}