티스토리 뷰

Frontend

Vue3 - vue3-virtual-scroller

hjkang 2026. 2. 3. 19:43

문제 상황

수천, 수만 개의 아이템을 리스트로 렌더링 할 때 일반적인 v-for 사용 시 브라우저가 모든 DOM 노드를 한 번에 생성

이는 초기 렌더링 시간을 지연시키고, 스크롤 성능을 크게 저하

 

 

virtual scroller란?

- 실제로 화면에 보이는 영역의 아이템만 DOM에 렌더링하는 기법

- 사용자가 스크롤 할 때 동적으로 보이는 아이템을 교체하여 모든 아이템이 렌더링된 것처럼 보이게 함

 

 

설치

npm install vue3-virtual-scroller

 

 

기본 사용법

// main.js
import { createApp } from 'vue'
import VueVirtualScroller from 'vue3-virtual-scroller'
import 'vue3-virtual-scroller/dist/vue3-virtual-scroller.css'

const app = createApp(App)
app.use(VueVirtualScroller)
app.mount('#app')

<template>
  <virtual-scroller
    :items="items"
    :item-height="50"
    class="scroller"
  >
    <template #default="{ item }">
      <div class="item">
        {{ item.name }}
      </div>
    </template>
  </virtual-scroller>
</template>

<script setup>
import { ref } from 'vue'

const items = ref(
  Array.from({ length: 10000 }, (_, i) => ({
    id: i,
    name: `Item ${i}`,
    content: `Content for item ${i}`
  }))
)
</script>

<style scoped>
.scroller {
  height: 500px;
}

.item {
  height: 50px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
</style>

 

주요 Props

- items: 렌더링할 데이터 배열

- item-height: 각 아이템의 고정 높이 (px)

- buffer: 뷰포트 위아래로 미리 렌더링할 아이템 수 (기본값: 5)

- key-field: 아이템 고유 식별자 필드명 (기본값: id)

 

 

동적 높이 처리

- 아이템마다 높이가 다른 경우에는 함수 전달 가능

<template>
  <virtual-scroller
    :items="items"
    :item-height="getItemHeight"
  >
    <template #default="{ item }">
      <div class="item" :class="item.type">
        {{ item.content }}
      </div>
    </template>
  </virtual-scroller>
</template>

<script setup>
const getItemHeight = (item) => {
  return item.type === 'large' ? 100 : 50
}
</script>

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함