Virtual scrolling for Vue 3: only the rows that are on screen are in the DOM, whether the list holds a hundred items or ten million.
Documentation and live examples: pdanpdan.github.io/virtual-scroll - that site is the manual: every feature is a running example with the code next to it.
Give it an array and a template for one row. It keeps the rows around the viewport in the DOM and positions them while the browser scrolls normally: a list of a million rows costs the same as a list of twenty, because only the visible rows exist.
Rows can be a vertical list, a horizontal strip, or a grid on both axes. The scroll container can be the component, an element around it, or the page. Row sizes can be a number, a value per row, or measured from the DOM as they change. Rows do not have to exist as objects: a sparse new Array(10_000_000) with content derived from index renders ten million rows without allocating ten million items.
Browsers refuse to scroll content past roughly 10 million pixels. The list is mapped onto the pixels the browser accepts, so a wheel notch or a swipe moves the content by the same distance as the input, regardless of the list size. The visible range, the scrollbar and scrollToIndex use the same coordinates.
Everything else is optional: sticky headers and sections, snapping, infinite loading, prepend restoration, RTL, keyboard navigation, ARIA roles, SSR, virtual scrollbars, TypeScript types, and dedicated components for table and masonry layouts. There are no dependencies besides Vue.
pnpm add @pdanpdan/virtual-scroll<script setup>
import { VirtualScroll } from '@pdanpdan/virtual-scroll';
import '@pdanpdan/virtual-scroll/style.css';
const items = Array.from({ length: 10000 }, (_, i) => ({ id: i, label: `Item ${ i }` }));
</script>
<template>
<VirtualScroll :items="items" :item-size="50" class="my-container">
<template #item="{ item, index }">
<div class="my-item">{{ index }}: {{ item.label }}</div>
</template>
</VirtualScroll>
</template>
<style scoped>
.my-container { height: 500px; }
.my-item { height: 50px; }
</style>Ten thousand rows, with about twenty in the DOM at any moment. Replace :item-size="50" with a function to size rows individually, or drop it altogether and rows get measured as they mount - the rest of the code stays as it is.
- Configurator / code generator: pdanpdan.github.io/virtual-scroll/configurator
- Comparison with other Vue 3 libraries: pdanpdan.github.io/virtual-scroll/compare
- Documentation for LLMs: llms.txt (in the repository)
- npm: npmjs.com/package/@pdanpdan/virtual-scroll
- Repository: github.com/pdanpdan/virtual-scroll
Five ways to use the package.
Standard way for most modern bundlers (Vite, Webpack). You must manually import the CSS file.
<script setup>
import { VirtualScroll } from '@pdanpdan/virtual-scroll';
import '@pdanpdan/virtual-scroll/style.css';
</script>Import the raw .vue file if you want to use your own Vue compiler configuration. All four components are exported this way: VirtualScroll.vue, VirtualScrollTable.vue, VirtualScrollMasonry.vue and VirtualScrollbar.vue.
<script setup>
import VirtualScroll from '@pdanpdan/virtual-scroll/VirtualScroll.vue';
// No need to import CSS separately
</script>useVirtualScroll returns the window to mount and the scroll state; you render and position the rows, and pass extensions as the second argument. Pass the scroll element as hostRef (or container), and give it a definite height.
<script setup>
import { useVirtualScroll } from '@pdanpdan/virtual-scroll';
import { computed, ref } from 'vue';
const scrollEl = ref(null);
const items = ref(Array.from({ length: 10_000 }, (_, i) => ({ id: i })));
const props = computed(() => ({ items: items.value, itemSize: 50, hostRef: scrollEl.value }));
const { renderedItems, scrollDetails } = useVirtualScroll(props);
</script>
<template>
<div ref="scrollEl" class="viewport">
<div :style="{ height: `${ scrollDetails.totalSize.height }px` }">
<div
v-for="row in renderedItems"
:key="row.index"
:style="{ transform: `translateY(${ row.offset.y }px)` }"
>
{{ row.item.id }}
</div>
</div>
</div>
</template>
<style scoped>
.viewport { height: 500px; overflow: auto; }
</style><!-- Import Vue 3 first -->
<script src="https://unpkg.com/vue@3"></script>
<!-- Import VirtualScroll CSS -->
<link rel="stylesheet" href="https://unpkg.com/@pdanpdan/virtual-scroll/dist/virtual-scroll.css">
<!-- Import VirtualScroll JavaScript -->
<script src="https://unpkg.com/@pdanpdan/virtual-scroll"></script>@pdanpdan/virtual-scroll/core publishes the same API with the optional wiring compiled out of the components that have it (VirtualScroll and VirtualScrollTable), for apps that only need virtualization:
<script setup>
import { VirtualScroll } from '@pdanpdan/virtual-scroll/core';
import '@pdanpdan/virtual-scroll/core/style.css';
</script>- Not included: custom scrollbars (the
virtualScrollbarprop and the#scrollbarslot), keyboard navigation, scroll snapping, sticky items, infinite loading and prepend restoration.VirtualScrollMasonryhas no such wiring to remove; the flow-mode scrollbar a table always shows for its own horizontal overflow is kept. - Still included: virtualization, dynamic measurement, RTL detection, coordinate scaling, inertia scrolling, ARIA roles, header/footer slots, the loading slot and SSR.
- Accepted but ignored in this build:
virtualScrollbar,snap,stickyIndices,loadDistanceandrestoreScrollOnPrependare kept in the type surface so a component can be swapped between the two entries, but they have no effect.loadingstill drives theloadingslot andaria-busy- only the automatic threshold that emitsloadis gone. Import from the package root when you need any of the rest.
A tree-shaken <VirtualScroll> is 18.7 KB gzipped from ./core and 24.9 KB from the package root. pnpm size enforces those budgets; the comparison page reports both entries including the stylesheet (18.0 kB and 23.4 kB). core/style.css is smaller than the full stylesheet, and both entries ship the same types.
Rows can be rendered purely from their index without storing any per-row data. Pass a sparse array - only its length is used - and derive the content from the slot's index:
<script setup>
import { VirtualScroll } from '@pdanpdan/virtual-scroll';
// Sparse placeholder: 10 million rows, zero data objects allocated.
const items = new Array(10_000_000);
</script>
<template>
<VirtualScroll :items="items" :item-size="40" class="my-container">
<template #item="{ index }">
<div class="my-item">Fixed Item {{ index }}</div>
</template>
</VirtualScroll>
</template>Notes:
itemsentries may beundefined(holes): every index in the rendered range produces a row, and theitemslot prop isundefinedfor holes. Don't readitemfields in the slot for such datasets.- Only indices in the visible window (plus buffer) are ever accessed from the
itemsarray. - Combined with a numeric
itemSize(arithmetic positioning, no per-row storage), uniform lists scale to 10M+ rows with flat memory - the playground essential examples use this pattern. - Dynamic (ResizeObserver-measured) sizes work the same way: sizes are measured from the rendered DOM.
Measured sizes belong to the item they were measured on, not to the index:
- Appending keeps every existing measurement.
- Prepending shifts the measurements by the number of added rows.
- Removing, reordering or replacing the array re-measures, because the stored sizes no longer describe the rows at those indices.
The first visible row stays where it is when rows above it are removed, when
the array is reordered, or when it is replaced by a list that still contains
that row. Set restoreScrollOnPrepend to keep the position for
prepends as well (chat history).
Content larger than the browser's scroll limit uses two coordinate systems:
- VU (virtual units): the real size of the content.
- DU (display units): the pixels the browser can scroll, capped at
BROWSER_MAX_SIZE.
A scale factor maps between them, so wheel and touch scrolling move the content 1:1 while the scrollbar and scrollToIndex use the virtual positions.
Rows are positioned with translateY() (or translateX() / translate()) from their virtual offset and the current display scroll position. Positions keep sub-pixel precision at any scale.
- Dynamic sizes: offsets are kept in a Fenwick tree, so a row measurement updates prefix sums in O(log N) without recomputing the list. Appends extend the tree instead of rebuilding it, and re-initialization only visits the regions that changed.
- Uniform sizes: a numeric
itemSize/columnWidthis resolved arithmetically, with no per-row storage. Combined with data-less rows, memory stays flat at any list size. - ResizeObserver: mounted rows are measured when their size changes.
- Style isolation: styles live in CSS
@layer, andcontain: layoutlimits layout work to the container. - Bundle budgets:
pnpm sizebuilds every published entry and one tree-shaken bundle per import scenario, then fails when an unused feature survives or an entry exceeds its gzipped budget (currently<VirtualScroll>24.9 KB,./core18.7 KB, headlessuseVirtualScroll12.0 KB,VirtualScrollTable26.1 KB,./coreVirtualScrollTable21.4 KB,VirtualScrollMasonry7.8 KB).
- Sizes: a number for every row, a function or repeating array for variable rows, or
ResizeObservermeasurement. - Repeating patterns: pass an array to
itemSizeorcolumnWidthto cycle sizes (e.g.[50, 100]). - Directions:
vertical,horizontalorboth(grid). - Virtual scrollbars: overlay bars that follow the pointer on lists of any size and look the same across browsers.
- Extensions: RTL, snapping, sticky items, infinite loading, prepend restoration and coordinate scaling.
- Scroll container: the component host, another element, or the browser
window/body. - SSR: pre-render a range of rows on the server (see SSR & Hydration).
- Accessibility: ARIA roles for lists, grids, trees, listboxes and menus.
Rows are recycled: they mount as they enter the viewport and unmount when they leave, so content should behave well under recycling:
- Keep row state in the model, not the DOM - selection, expansion, and likes belong in your data/store keyed by item id; anything stored in the element vanishes when the row scrolls away.
- Make row rendering idempotent - the
itemslot re-renders on every entry into the window; rendering the same item twice must produce the same result. - Reserve space for media - explicit
width/heightoraspect-ratioprevents post-mount row growth (which the engine measures and corrects, but which causes jumps). - Avoid native
loading="lazy"on images - the visible window is already the only mounted content; lazy-loading adds browser heuristics on a changing scroll container and can starve on-screen images. Use eager loading or your own bounded, low-priority prefetch window. - Dynamic heights - late content growth is measured with
ResizeObserverand the layout corrects itself; stable or reserved sizes scroll more smoothly (see "Authoring Content for Virtualized Lists" in the docs).
Extensions hook into the scroll lifecycle. The built-in ones are below; custom extensions implement the same contract.
An extension is a plain object implementing VirtualScrollExtension<T>: a unique name plus the
optional hooks onInit(ctx), includeIndices(ctx), onScroll(ctx, event), onScrollEnd(ctx) and
transformRenderedItems(items, ctx) (post-processes the rendered window and must return the items to
render). includeIndices returns extra item indices that must stay in the rendered window even when
they are outside the visible range (the sticky extension pins the previous sticky item that way); the
engine merges, de-duplicates and sorts them. Every hook receives an ExtensionContext<T> with the
reactive props, scrollDetails, totalSize, range and currentIndex, the engine state refs
(internalState, including isHydrated) and the engine methods (scrollToIndex, scrollToOffset,
updateDirection, getRowIndexAt, getColumnIndexAt, getItemSize, getItemBaseSize,
getItemOffset, getColumnWidth, getColumnOffset, getItemRawOffset,
handleScrollCorrection). The axis-specific resolvers matter on a grid, where getItemSize and
getItemOffset describe rows while getColumnWidth and getColumnOffset describe columns. name
is only a label: hooks are called in the order the extensions are passed to useVirtualScroll.
useRtlExtension(): Right-to-Left layout support. Direction detection belongs to the engine (it re-reads it on mount, on resize, on scroll and ondir/stylechanges); the extension asks for that read while initializing, so the first render already has the direction.useSnappingExtension(): Item snapping after scroll stops.useStickyExtension(): Sticky header/footer and index support. It owns the pinning itself: the previous sticky item stays rendered while it is scrolled past, andisStickyActive/stickyOffsetare computed here.stickyIndiceswithout this extension keeps the layout offsets but pins nothing.useInfiniteLoadingExtension({ onLoad, flingVelocity, preload }): Trigger loading when reaching thresholds.onLoad(axis, { velocity, direction })receives the scroll velocity (VU/ms) and travel direction;flingVelocity(default2) skips the callback while the axis is still flinging, andpreload(VU, default0) extends the threshold only while scrolling towards the end.useSnapshotsExtension({ storage, key, autoSave }): Save and restore the visible position (save(),restore(),clear()), optionally persisted throughsessionStorage/localStorageor a customStorage.usePrependRestorationExtension(): Maintain scroll position when items are prepended.useCoordinateScalingExtension(): Supports content beyond the browser's scroll limit.
When using the VirtualScroll component, extensions are already integrated. If you use the useVirtualScroll composable directly, you can pass them as the second argument:
import {
useRtlExtension,
useSnappingExtension,
useVirtualScroll,
} from '@pdanpdan/virtual-scroll';
// eslint-disable-next-line unused-imports/no-unused-vars, no-undef
const { renderedItems, scrollDetails } = useVirtualScroll(props, [
useRtlExtension(),
useSnappingExtension(),
]);These composables expose the engine directly.
Everything in this document imports from the package root. The engine layer the components are built on -
the pure calculation helpers (calculate*), the DOM scroll helpers, the sizing layer
(useVirtualScrollSizes) and the parameter bags they take - is published from
@pdanpdan/virtual-scroll/internal; that entry also carries the masonry layout engine and its types,
which the root entry never exported. Nothing there is covered by semver: shapes and signatures may
change in any release, including a patch, and the source is the documentation. (FenwickTree, the structure the sizing layer builds on,
is exported from the root; its methods are listed in the API reference.)
The core logic for virtualization.
Parameters:
props: Reactive object,Refor getter for VirtualScrollProps.extensions: Optional array of VirtualScrollExtension objects.
Returns:
The Exposed Members list covers the properties and methods the component puts on its instance; the composable returns those plus totalWidth / totalHeight, renderedVirtualWidth / renderedVirtualHeight, isWindowContainer, scrollbarOffset, handleScrollCorrection and scrollCorrection - a Ref<Point> holding the correction the engine applied to the scroll position when sizes above the window changed, which extensions and drag emulation use to keep their own origin in sync (see Type Definitions for the shapes).
Logic for custom virtual scrollbar interactions (dragging, clicking).
Props:
axis:'vertical' | 'horizontal'totalSize: Content size (DU).viewportSize: Viewport size (DU).position: Current scroll (DU).scrollToOffset: Callback to update scroll.containerId(optional): id of the controlled container, exposed asaria-controls.isRtl(optional): Map the thumb for RTL layouts.ariaLabel(optional): Accessible label for the track.
Returns:
trackProps/thumbProps: Attributes/listeners to bind on the track and thumb (role, ARIA values, styles, pointer handlers).trackStyle/thumbStyle: Calculated reactive styles.positionPercent/viewportPercent(0-1),thumbSizePercent/thumbPositionPercent(0-100): Raw geometry for custom interfaces.isDragging: Drag state.
Handles pointer-based scrolling, inertia animation, and mouse wheel events for cases where native scrolling is not available (e.g., massive lists or custom scrollbars).
Config:
useVirtualScrolling: Boolean ref.scrollDetails: Reactive ScrollDetails.scrollToOffset: Method to update scroll position.stopProgrammaticScroll: Method to halt animations.
Returns:
isPointerScrolling: Boolean ref.handlePointerDown/Move/Up: Event handlers for pointer interaction.handleWheel: Event handler for mouse wheel.stopInertia(): Method to cancel ongoing momentum.shiftOrigin(deltaX, deltaY): Moves the origin a drag measures from, so a measurement correction that shifted the content does not get undone by the next pointer move. No-op when no drag is in progress.
Provides keyboard navigation (Arrows, Home, End, PageUp, PageDown) for the virtual scroll container, either by scrolling the viewport or by moving a roving active item.
Config:
props: Props of the list being navigated - a plain object, aRefor a getter, so bounds, axis and column count stay live when the configuration is derived.scrollDetails: Reactive ScrollDetails.scrollToIndex: Method to scroll to a specific index.scrollToOffset: Method to scroll to a pixel position. For theEndkey the composable requests extra range beyond the virtual content end (engineendExtraX/endExtraYoptions), so an always-rendered loading slot below the items stays reachable.stopProgrammaticScroll: Method to halt animations.getLoadingSlotSize(optional): Height of the loading slot. When provided,Endincludes it in the target so the last item plus the slot fit in the viewport....resolvers: Various helper functions for index/offset mapping.activationMode(optional, accepts a ref or getter):'viewport'(default) scrolls the viewport only, with no active item;'item'moves a roving active item and exposes it throughactiveIndex/isActive/aria-activedescendant. The component derives it from the container role - seekeyboardActivation.onActivate(optional): Called with the item index when the active item is activated -Enter/Spaceon the container, or an explicithandleItemActivatecall. Never called in'viewport'mode.
Key behavior ('item' mode):
- Arrows: Move the active item by one along the scroll axis (
ArrowLeft/ArrowRighton horizontal lists, honouring RTL; in grid mode the active item is a row, so the inline arrows keep panning columns) and scroll it back into view only when it left the viewport. The first arrow press activates the first visible item without scrolling. PageUp/PageDown/Home/End: Move the active item one viewport up/down, or to the first/last item, and keep it visible. The other axis is left untouched, so a multi-column list keeps its current column.Enter/Space: Activate the active item throughonActivate.
Key behavior ('viewport' mode):
Home/End: Scroll to the start / end of the content.Endscrolls tototalSize - viewportSize(plus the loading slot size whengetLoadingSlotSizeis provided); the target is re-clamped when measurements settle, and new content appended by a load is not chased automatically. Because the slot lives in the DOM after the virtual wrapper, the requested range also extends the engine's scroll clamp, so the slot stays reachable.PageUp/PageDown: Scroll by one full page. The target is the first visible item minus one (startIdx - 1) / the last visible item plus one (endIdx + 1), so each press advances exactly one viewport.- Arrows: Move one item in the scroll direction (one column in grid mode).
Enter/Spacedo nothing.
Returns:
handleKeyDown: Keyboard event handler.activeIndex:Ref<number>with the roving active item index,-1when none.liveMessage:Ref<string>with the polite announcement for the active item, e.g.Item 21 of 100(empty when nothing is active).handleItemActivate(index): Marks an item active and callsonActivate(e.g. from a click handler in the item slot). No-op in'viewport'mode.
Manages ResizeObserver instances for the container, items, and slots (header/footer) to support fully dynamic sizing.
Config:
hostRef/wrapperRef: Element references.headerRef/footerRef: Slot references.itemRefs: Map for tracking rendered item elements.updateHostOffset: Method to recalculate container position.updateItemSizes: Method to register batch measurements.
Returns:
setItemRef(el, index): Callback ref for individual items.
The engine behind VirtualScrollMasonry: derives the column geometry from the container width, places each card on the shortest column, mounts only the window around the scroll position and keeps the topmost visible card in place when the layout changes.
Parameters:
props: Reactive object,Refor getter for the masonry props plushostRef(the scroll container element).
Returns:
renderedCards: Cards to mount in the current window.scrollDetails: ReactiveMasonryScrollDetails(currentIndex/currentEndIndex,range,scrollOffset.y,viewportSize,totalSize,isScrolling, β¦).columns/columnWidth/totalHeight/totalHeightExact: reactive column geometry and content height.scrollToIndex(index, options)/scrollToOffset(offset, options)/refresh(): programmatic API.internalState/applyMeasurements(...): consumed by the component wrapper and tagged@internal- not part of the supported surface.
For tabular data use the dedicated VirtualScrollTable component instead: it renders a real <table> structure with optional real-table-flow rows (flowTable, supporting measured dynamic row heights), sticky header/footer slots, and three column-width strategies - browser auto layout, first-window auto-sizing (autoSizeColumns), or explicit columnWidths; overflowing tables get a horizontal scrollbar. See the Flow Table example.
The table fixes its own semantic tags (table > tbody > tr, with thead/tfoot for the slots), so the containerTag/wrapperTag/itemTag/headerTag/footerTag props do not apply to it - they are typed on VirtualScroll, which is the component to use when you need ul/ol > li markup.
For a masonry grid inside a single scroll container use VirtualScrollMasonry: the column count and a fractional column width come from the container width, cards go to the shortest column, and only the window around the scroll position is mounted. Heights come from the itemHeight function: a scrollToIndex target is computed without mounting the cards in between, the total is exact once the layout reaches the end (totalHeightExact), and a reflow keeps the topmost visible card in place. See the Masonry example. For server rendering, pass ssrWidth and ssrCount: the grid is laid out from that width on the server, the first client render repeats it, and the measured width takes over after mount.
<VirtualScrollMasonry
ref="masonryRef"
:items="items"
:item-height="itemHeight"
:target-column-width="240"
:min-columns="2"
:max-columns="8"
:gap="16"
@scroll="onScroll"
>
<template #item="{ item, index, column, width, height }">
<div class="card" :style="{ height: '100%', backgroundColor: item.color }">
#{{ index }} Β· col {{ column }} Β· {{ Math.round(height) }}px
</div>
</template>
</VirtualScrollMasonry>Masonry-specific props:
| Prop | Type | Default | Description |
|---|---|---|---|
itemHeight |
fn(item, index, columnWidth) |
Required | Canonical height oracle in px. Must be deterministic: the same (index, columnWidth) must always return the same height, because placements are committed to a frontier chain. Non-finite results fall back to 40; finite non-positive results clamp to 1. |
measuredHeights |
boolean |
false |
Measure mounted cards with a ResizeObserver and drive the layout from the measured boxes ("local" determinism). Off: canonical oracle layout, nothing measured. On: cards size to their content (the oracle height becomes the pre-measure minimum) and every measurement batch re-lays-out with the viewport re-anchored. |
targetColumnWidth |
number |
240 |
Desired column width in px; the column count is derived so columns land as close as possible to it. |
ssrWidth / ssrCount |
number |
- | Server rendering: lay the grid out from ssrWidth and mount the first ssrCount cards before the container is measured. Pass both; after mount the measured width takes over. |
minColumns / maxColumns |
number |
1 / 10 |
Column count bounds for responsive reflow. |
gap |
number |
10 |
Spacing between cards, both between columns and rows. |
segmentSize |
number |
500 |
Items per stored frontier snapshot (memory vs. chain-step tradeoff). |
virtualScrollbar |
boolean |
true |
Overlay scrollbar over the native one (native bar is hidden while enabled). |
debug |
boolean |
false |
Outline card bounds and show a geometry badge per card. |
role / ariaLabel / ariaLabelledby / itemRole |
string |
- | ARIA semantics (wrapper defaults to list with listitem cards). |
All VirtualScroll items/itemSize/direction/snap/sticky/table props do not apply to the masonry component.
- Item slot props:
{ item, index, column, x, y, width, height }(px, relative to the cards wrapper). - Events:
scrollwithMasonryScrollDetails(items,currentIndex/currentEndIndex,range,scrollOffset.y,viewportSize,totalSize,isScrolling, β¦). - Exposed (via ref):
scrollDetails,columns,columnWidth,totalHeight,totalHeightExact,scrollToIndex(index, { align, behavior }),scrollToOffset(offset),refresh().
Masonry sizing contract: in the default canonical mode cards must render at exactly the oracle height - reserve media space (
aspect-ratio, fixed model heights, β¦) and never rely on DOM measurement. WithmeasuredHeightscards size to their content instead and the measured box drives the layout (mounted cards only; unmounted regions fall back to the oracle, and measurements reset when theitemsarray is replaced). In-place item edits or oracle changes need arefresh()(or a newitemsarray) to re-layout; relayouts keep the topmost visible card pinned at its screen offset. Vertical axis only: no RTL/horizontal/both mode and no coordinate scaling - very tall datasets stay below the browser's ~10M px scroll limit.
| Prop | Type | Default | Description |
|---|---|---|---|
items |
T[] |
Required | Array of items to be virtualized. May contain undefined entries (e.g. new Array(n) for data-less lists): every index in range renders and item is undefined for holes; only the visible window is accessed. |
itemSize |
number | (number | null | undefined)[] | fn | null |
undefined |
Fixed size, repeating array pattern (holes and null mean "measure this index"), or function. Omit it (or pass 0/null) and rows are measured with a ResizeObserver, using defaultItemSize (40) as the pre-measure estimate. |
direction |
'vertical' | 'horizontal' | 'both' |
'vertical' |
Scroll direction. |
columnCount |
number |
0 |
Number of columns for grid mode. |
columnWidth |
num | (num | null | undefined)[] | fn | null |
undefined |
Column sizing for grid mode (same forms as itemSize). Omit it (or pass 0/null) and columns are measured, using defaultColumnWidth (100) as the pre-measure estimate. |
gap / columnGap |
number |
0 |
Spacing between items/columns. |
snap |
SnapMode |
false |
Enable scroll snapping. See SnapMode. |
stickyIndices |
number[] |
[] |
Indices of items that should remain sticky. When stickyHeader/stickyFooter are enabled, they stick below/above them. |
stickyHeader / stickyFooter |
boolean |
false |
If true, measures and adds slot size to padding. Sticky stickyIndices items align below/above them. |
ssrRange |
object |
- | Range of items to pre-render for SSR. |
virtualScrollbar |
boolean |
false |
Whether to force virtual scrollbars. |
restoreScrollOnPrepend |
boolean |
false |
Keep the scroll position when items are added to the top. |
loading |
boolean |
false |
While true, reveals the #loading slot (kept mounted and hidden via CSS while false) and suppresses repeated load events. |
loadDistance |
number |
200 |
Distance from the end (DU) at which the load event triggers. |
container |
HTMLElement | Window |
hostRef |
The scrollable container element. |
containerTag |
string |
'div' |
HTML tag for the root container. |
wrapperTag |
string |
'div' |
HTML tag for the items wrapper - pair 'ul'/'ol' with itemTag: 'li' for semantic lists. |
itemTag |
string |
'div' |
HTML tag for each virtualized item. For tabular data use VirtualScrollTable instead. |
headerTag |
string |
'div' |
HTML tag for the header slot wrapper (e.g. 'header'). |
footerTag |
string |
'div' |
HTML tag for the footer slot wrapper (e.g. 'footer'). |
scrollPaddingStart / End |
num | {x, y} |
0 |
Padding for scroll calculations. |
bufferBefore / bufferAfter |
number |
5 |
Items to render outside the viewport. |
initialScrollIndex |
number |
undefined |
Index to jump to on mount. |
initialScrollAlign |
ScrollAlignment | ScrollAlignmentOptions |
'start' |
Alignment for initial jump. See ScrollAlignment or Options. |
defaultItemSize / defaultColumnWidth |
number |
40 / 100 |
Estimate for dynamic items/columns. |
debug |
boolean |
false |
Enable debug visualization. |
role |
string |
- | ARIA role for the container. Defaults based on direction. |
keyboardActivation |
'auto' | 'item' | 'viewport' |
'auto' |
How the keyboard interacts with the content. 'auto' uses the roving item model for the roles that publish an active descendant (listbox, menu, tree) and viewport scrolling for everything else, including the default grid role of a two-axis list. 'item' always tracks an active item; 'viewport' never does. |
ariaLabel / ariaLabelledby |
string |
- | Accessibility labels for the container (the container role becomes region when either is set). |
itemRole |
string |
- | ARIA role for items. Defaults based on role. |
Controls the automatic alignment after scrolling stops.
false(default): No snapping.true/'auto': Snapping follows the scroll direction: acts as'end'when scrolling towards start, and'start'when scrolling towards end.'next': Snaps to the next (closest) snap position in the direction of the scroll.'start': Aligns the first visible item to the viewport start if at least 50% visible, otherwise aligns the next item.'center': Aligns the item that intersects the viewport center to the center.'end': Aligns the last visible item to the viewport end if at least 50% visible, otherwise aligns the previous item.
Snapping is disabled if the target item's size is larger than the viewport dimension.
Controls the item's final position in the viewport during scrollToIndex.
'start': Aligns to top (vertical) or left (horizontal) edge.'center': Aligns to viewport center.'end': Aligns to bottom (vertical) or right (horizontal) edge.'auto'(default): No scroll if the item is already fully visible; otherwise aligns to'start'or'end'to bring it into view.
Allows axis-specific alignment in scrollToIndex.
x:ScrollAlignmentfor the horizontal axis.y:ScrollAlignmentfor the vertical axis.
| Event | Payload | Description |
|---|---|---|
scroll |
ScrollDetails<T> |
Emitted on every scroll-details change once hydrated. See ScrollDetails. |
visibleRangeChange |
{ start, end, colStart, colEnd } |
Emitted when the rendered range changes, and once on hydration. start/colStart are inclusive and end/colEnd exclusive, matching ScrollDetails range/columnRange. |
load |
'vertical' | 'horizontal', LoadDetails |
Emitted when the scroll position comes within loadDistance (DU) of the end on that axis; suppressed while loading is true and while the axis is flinging faster than flingVelocity. The second argument carries { velocity, direction } (velocity in VU/ms, direction 'start' | 'end' | null). |
itemActivate |
index: number, item: T | undefined |
Emitted when the active item is activated with Enter/Space, or from an explicit handleItemActivate(index) call (e.g. a click in the item slot). Only emitted in the item activation model. |
VirtualScrollTable emits the same events. VirtualScrollMasonry emits scroll with MasonryScrollDetails (single vertical axis).
item: Scoped slot for individual items. Providesitem(may beundefinedfor holes in sparse/index-only datasets - type the array as(T | undefined)[]to model that),index,getItemAriaProps,getCellAriaProps,columnRange,getColumnWidth,gap,columnGap,isSticky,isStickyActive,isStickyActiveX,isStickyActiveY,isActive,offset.header/footer: Content rendered at the top/bottom of the scrollable area.loading: Content rendered at the end while loading. The slot is always rendered when provided - it is hidden via thevirtual-scroll-loading--hiddenclass (visibility: hidden) whileloadingis false - so it reserves its space andEndcan include its size in the scroll target. Only provide the slot while a load is expected: once there is no more data (or loading is disabled), stop passing it (e.g.v-if="hasMore"on<template #loading>) and the reserved space disappears.scrollbar: Scoped slot for custom scrollbar. Called once for each active axis.axis:'vertical' | 'horizontal'positionPercent: current position (0-1).viewportPercent: viewport percentage (0-1).thumbSizePercent: Calculated thumb size (0-100).thumbPositionPercent: Calculated thumb position (0-100).trackProps: Attributes/listeners for the track. Bind withv-bind="trackProps".thumbProps: Attributes/listeners for the thumb. Bind withv-bind="thumbProps".scrollbarProps: Grouped props for theVirtualScrollbarcomponent.isDragging: Whether the thumb is currently being dragged.
The following properties and methods are available on the VirtualScroll component instance (via template ref).
- All Props: All properties defined in Props are available on the instance.
scrollDetails: Full reactive state of the virtual scroll system. See ScrollDetails.activeIndex: Index of the item tracked by keyboard navigation,-1when none.setActiveIndex(index): Sets (nullclears) the active item without scrolling, so a click or an external selection can be synced in.columnRange: Information about the current visible range of columns. See ColumnRange.wrapperRole/cellRole: The ARIA roles currently applied to the items wrapper and its cells.isHydrated:truewhen the component is mounted and hydrated.isRtl:trueif the container is in Right-to-Left mode.scrollbarPropsVertical/scrollbarPropsHorizontal: ReactiveScrollbarSlotProps.scaleX/scaleY: Current coordinate scaling factors (VU/DU).renderedWidth/renderedHeight: Physical dimensions in DOM (clamped, DU).componentOffset: Absolute offset of the component within its container (DU).
setActiveIndex(index): Sets the active item without scrolling (nullclears it), for syncing a click or an external selection.handleItemActivate(index): Marks an item active and emitsitemActivate.scrollToIndex(row, col, options): Programmatic scroll to index. An end-anchored scroll (last row or content end) keeps re-clamping while settling measurements move the real end, so the first jump to the end lands flush even on dynamic lists. A user scroll during a smooth animation cancels it. See ScrollToIndexOptions.scrollToOffset(x, y, options): Programmatic scroll to pixel position. The target is re-clamped when measurements settle (dynamic items), mirroringscrollToIndex's deferred settling. See ScrollToOffsetOptions.refresh(): Resets all measurements and state.stopProgrammaticScroll(): Halt smooth scroll animations and inertia.updateDirection(): Manually trigger direction detection.updateHostOffset(): Recalculate component position.remeasureItem(index): Re-read one rendered item from its element; returnsfalsewhen it is not rendered.updateItemSize(index, inlineSize, blockSize, el?): Register single measurement.updateItemSizes(updates): Batch register measurements.getRowHeight(index): Returns the calculated height of a row.getColumnWidth(index): Returns the calculated width of a column.getRowOffset(index): Returns the virtual offset of a row.getColumnOffset(index): Returns the virtual offset of a column.getItemOffset(index): Returns the virtual offset of an item.getItemSize(index): Returns the size of an item along the scroll axis.getRowIndexAt(offset): Returns the row index at a virtual offset.getColumnIndexAt(offset): Returns the column index at a virtual offset.getCellAriaProps(colIndex): Returns ARIA attributes for a grid cell.getItemAriaProps(index): Returns ARIA attributes for a row/item.
The component automatically manages ARIA roles and attributes to ensure screen readers can navigate the virtualized content.
In the item keyboard model, aria-activedescendant points at the active row only while that row is rendered, so the reference is always valid. The active index lives in the data: it returns to the attribute when the row scrolls back in, and it clamps to the last row when the list shrinks. If a focused control inside a row unmounts (the row scrolled out, or its item was removed), focus returns to the scroll container; it stays where it is when another control already has focus.
| Role Prop | Default Item Role | Usage Case |
|---|---|---|
list |
listitem |
Standard vertical or horizontal list. |
grid |
row |
Bidirectional grid or table. |
tree |
treeitem |
Hierarchical list. |
listbox |
option |
Selection lists. |
menu |
menuitem |
Navigational menus. |
aria-rowcount, aria-colcount, aria-rowindex, and aria-colindex are automatically calculated and applied based on the current scroll state.
With keyboardActivation set to the item model - 'auto' selects it for listbox, menu and tree - the container also publishes aria-activedescendant pointing at the active item's id, and a polite live region announces the active position (Item 21 of 100) as it moves. Enter/Space emit itemActivate; a click routed through handleItemActivate(index) does the same.
| Property | Type | Description |
|---|---|---|
items |
RenderedItem[] |
List of items currently in DOM. |
currentIndex |
number |
Index of the first visible row below any sticky header. |
currentEndIndex |
number |
Index of the last visible row above any sticky footer. |
currentColIndex |
number |
Index of the first visible column after any sticky column. |
currentEndColIndex |
number |
Index of the last visible column before any sticky end column (grid mode). |
scrollOffset |
Point |
Current virtual scroll position (VU). |
displayScrollOffset |
Point |
Current physical scroll position (DU). |
viewportSize |
Size |
Dimensions of visible area (VU). |
displayViewportSize |
Size |
Physical dimensions of visible area (DU). |
totalSize |
Size |
Total size of all items (VU). |
isScrolling |
boolean |
Whether scrolling is active. |
isProgrammaticScroll |
boolean |
Whether scroll was triggered via API. |
range |
{start, end} |
Range of rendered item indices. |
columnRange |
ColumnRange |
Range of rendered columns. |
| Property | Type | Description |
|---|---|---|
start |
number |
First rendered column index. |
end |
number |
Last rendered column index (exclusive). |
padStart |
number |
Virtual padding at the start of the row (VU). |
padEnd |
number |
Virtual padding at the end of the row (VU). |
| Property | Type | Default | Description |
|---|---|---|---|
align |
ScrollAlignment | ScrollAlignmentOptions |
'auto' |
Alignment logic. |
behavior |
'auto' | 'smooth' |
'smooth' |
Scroll animation. |
| Property | Type | Default | Description |
|---|---|---|---|
behavior |
'auto' | 'smooth' |
'auto' |
Scroll animation. |
endExtraX |
number |
0 |
Extra scrollable range (VU) after the content end on the X axis, so a block rendered after the items (e.g. an always-rendered loading slot) stays reachable. |
endExtraY |
number |
0 |
Same as endExtraX on the Y axis. |
| Option | itemSize / columnWidth |
Cost | Description |
|---|---|---|---|
| Fixed | number (e.g. 50) |
One multiplication per row, no per-row storage | Every item has the same size. |
| Array | number[] |
One lookup per row | Repeating pattern: entries cycle for items or columns when the array is shorter than the data. |
| Function | (item, index) => number |
One call per row | The size is known but varies per item. |
| Dynamic | 0, null or undefined |
ResizeObserver per mounted row |
Sizes are measured from the DOM. |
Virtual scrollbars are automatically enabled when content size exceeds browser limits, but can be forced via the virtualScrollbar prop.
Virtual scrollbars and coordinate scaling are disabled when the container is the browser window or body; native scrolling is used instead.
You can use the built-in VirtualScrollbar independently if needed.
| Prop | Type | Default | Description |
|---|---|---|---|
axis |
'vertical' | 'horizontal' |
'vertical' |
Axis this scrollbar drives. |
totalSize |
number |
Required | Content size (DU). |
position |
number |
Required | Current scroll position (DU). |
viewportSize |
number |
Required | Viewport size (DU). |
scrollToOffset |
(offset: number) => void |
- | Called with the requested offset while dragging or clicking the track. The same value is emitted as scrollToOffset, so either channel works. |
containerId |
string |
- | id of the controlled container, exposed as aria-controls. |
isRtl |
boolean |
false |
Map the thumb for RTL layouts. |
ariaLabel |
string |
- | Accessible label for the track. The component renders none by default; VirtualScroll passes "Vertical scroll" / "Horizontal scroll". |
The component itself exposes nothing through a template ref; use the useVirtualScrollbar composable when you need the geometry.
<script setup>
import { VirtualScrollbar } from '@pdanpdan/virtual-scroll';
import { ref } from 'vue';
const scrollX = ref(0);
const scrollY = ref(0);
</script>
<template>
<div class="my-container relative overflow-hidden">
<VirtualScrollbar
axis="vertical"
:total-size="10000"
:viewport-size="500"
:position="scrollY"
@scroll-to-offset="val => scrollY = val"
/>
<VirtualScrollbar
axis="horizontal"
:total-size="10000"
:viewport-size="800"
:position="scrollX"
@scroll-to-offset="val => scrollX = val"
/>
</div>
</template>The scrollbar slot provides everything needed to build a fully custom interface using v-bind. It is called once for each active axis.
<template>
<VirtualScroll :items="items" direction="both" virtual-scrollbar>
<template #scrollbar="{ trackProps, thumbProps, axis }">
<!-- Handle axes separately -->
<div v-if="axis === 'vertical'" v-bind="trackProps" class="custom-v-track">
<div v-bind="thumbProps" class="custom-v-thumb" />
</div>
<div v-else v-bind="trackProps" class="custom-h-track">
<div v-bind="thumbProps" class="custom-h-thumb" />
</div>
</template>
</VirtualScroll>
</template>| Variable | Default (Light/Dark) | Description |
|---|---|---|
--vs-scrollbar-bg |
rgba(230,230,230,0.9) / rgba(30,30,30,0.9) |
Track background color. |
--vs-scrollbar-thumb-bg |
rgba(0,0,0,0.3) / rgba(255,255,255,0.3) |
Thumb background color. |
--vs-scrollbar-thumb-hover-bg |
rgba(0,0,0,0.6) / rgba(255,255,255,0.6) |
Thumb background on hover/active. |
--vs-scrollbar-size |
8px |
Width (vertical) or height (horizontal) of the scrollbar. |
--vs-scrollbar-radius |
4px |
Border radius for track and thumb. |
--vs-scrollbar-cross-gap |
var(--vs-scrollbar-size) |
Size of gap where scrollbars meet. |
--vs-scrollbar-has-cross-gap |
0 |
If gap should be shown where scrollbars meet. |
MIT