跪拜 Guibai
← Back to the summary

vue-virtualize: A Zero-Dependency Vue3 Virtual List That Keeps 100K Rows Smooth

100,000 rows scroll without lag? Talking about the virtual list component vue-virtualize I wrote

The most common long-list scenario in admin systems: user lists, log streams, order records, often tens of thousands of entries. Directly rendering with v-for creates tens or even hundreds of thousands of DOM nodes, causing white screens on first paint, scroll jank, and a collapsing experience.

Virtual list is the standard solution: render only the visible region, keep the DOM count constant, and decouple performance from data size. I packaged it into a zero-dependency Vue3 component vue-virtualize. This article explains its principle and implementation in depth.

一、See the effect first

With 100,000 rows, scrolling is smooth and the DOM nodes stay at just a few dozen:

<script setup lang="ts">
import { ref } from 'vue'
import { VirtualList } from 'vue-virtualize'

const list = ref(Array.from({ length: 100000 }, (_, i) => ({ id: i, text: `第 ${i} 条数据` })))
const listRef = ref()

function jump() {
  listRef.value?.scrollToIndex(50000, 'center') // jump to the 50000th item
}
</script>

<template>
  <button @click="jump">Jump to item 50000</button>
  <VirtualList ref="listRef" :items="list" :item-size="40" height="400px" :buffer="8" key-field="id">
    <template #default="{ item, index }">
      <div style="height: 40px; line-height: 40px; border-bottom: 1px solid #eee">
        {{ index }}. {{ item.text }}
      </div>
    </template>
  </VirtualList>
</template>

Online demo: https://lcy-24.github.io/vue-virtualize/

二、Core principle: stretch height + position + render only the window

The three pillars of a virtual list:

  1. Outer scrollable container with fixed height and overflow-y: auto.
  2. An inner spacer element with height = items.length × itemSize, making the scrollbar appear as long as 100,000 rows.
  3. Render only items in the [start, end] range, each absolutely positioned to the correct offset.
<template>
  <div ref="containerRef" class="vv-list" :style="containerStyle" @scroll="onScroll">
    
    <div class="vv-list__spacer" :style="{ height: totalHeight + 'px', position: 'relative', width: '100%' }">
      
      <div v-for="vi in visibleItems" :key="..." class="vv-list__item" :style="vi.style">
        <slot :item="vi.item" :index="vi.index" />
      </div>
    </div>
  </div>
</template>

Here totalHeight = items.length * itemSize, and visibleItems only contains items in the [start, end] range.

三、Core calculation: scroll position → start/end indices

const startIndex = computed(() =>
  Math.max(0, Math.floor(scrollTop.value / props.itemSize) - props.buffer)
)

const endIndex = computed(() =>
  Math.min(
    props.items.length,
    Math.ceil((scrollTop.value + viewportHeight.value) / props.itemSize) + props.buffer
  )
)

const visibleItems = computed<VisibleItem[]>(() => {
  const result: VisibleItem[] = []
  for (let i = startIndex.value; i < endIndex.value; i++) {
    result.push({
      item: props.items[i],
      index: i,
      style: {
        position: 'absolute',
        top: `${i * props.itemSize}px`,   // absolute position to correct offset
        height: `${props.itemSize}px`,
        left: '0', right: '0',
      },
    })
  }
  return result
})

Three key points:

  1. buffer (overscan): render a few extra items outside the viewport. Otherwise, when scrolling fast, new items haven't appeared yet and you see white flashes. buffer defaults to 6, meaning 6 extra items above and below.
  2. Absolute positioning + top calculation: because the spacer is position: relative, a child's absolute top is its real offset in the whole list, so the render window always aligns correctly.
  3. keyField custom key: the default key is index, but if list items are components with interactive internal state, index reuse during scrolling causes state mixing. Specifying keyField="id" and using the real id as the key avoids that.

四、Adaptive viewport + targeted scrolling

Adaptive: container height may change (window resize, layout adjustments), so use ResizeObserver to watch and recompute viewportHeight:

onMounted(() => {
  updateViewport()
  if (typeof ResizeObserver !== 'undefined' && containerRef.value) {
    resizeObserver = new ResizeObserver(updateViewport)
    resizeObserver.observe(containerRef.value)
  }
})
onBeforeUnmount(() => resizeObserver?.disconnect())

Targeted scrolling: this is a capability plain v-for lists don't have—precisely jumping to the Nth item:

function scrollToIndex(index: number, align: 'start' | 'center' | 'end' = 'start') {
  const el = containerRef.value
  if (!el) return
  const target = Math.min(Math.max(index, 0), props.items.length - 1)
  let top = target * props.itemSize
  if (align === 'center') top -= (el.clientHeight - props.itemSize) / 2
  else if (align === 'end') top -= el.clientHeight - props.itemSize
  el.scrollTop = Math.max(0, top)
}

With fixed height, the offset of the Nth row is N × itemSize, and align controls where in the viewport it lands. Exposed via defineExpose, it's callable through a ref.

五、Limitations: why it's "fixed height"

This component is a fixed-height virtual list (itemSize is constant). It covers 80% of scenarios—tables, logs, streams of equal-height rows. But dynamic-height lists (like masonry or rich-text cards) require measuring each item's height, which adds an order of magnitude in complexity, and is out of scope for this library. The README states this clearly to avoid misleading users.

六、Pitfalls encountered

  1. The key with index pitfall. In the first version I used index as the key for simplicity, but when list items contained input boxes with v-model, scrolling would mix up the input values. Adding keyField fixed it.
  2. Building type declarations. For .vue components, using defineProps<Props>() with Vite to build declaration files throws a "cannot be named" error. The final solution is vite build for JS/CSS and vue-tsc separately to produce .d.ts, which is solid (also mentioned in the vue-crud-schemas post; a common pitfall in component library builds).
  3. Should scroll events be throttled? In my testing, the scroll handler only assigns scrollTop and recomputes a computed (a few dozen items), far from needing throttling; adding it introduces latency instead. The performance bottleneck is DOM count, not computation.

Final words

Virtual lists are typical of "high-frequency in interviews + real need in work". The principle isn't complex, but packaging it into a type-safe, overscan-aware, adaptive, and scrollable component requires attention to many details. This library came from optimizing lists in a data console, and I hope it helps those tormented by long lists.

Welcome stars, issues, and improvements.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

Rendering only the visible area is a solid move; with a hundred thousand items the DOM stays constant at a few dozen, the approach is remarkably clean. That pitfall of using index as the key causing row misalignment is pinpointed accurately.