Blog>
Snippets

Using Virtual Scrolling with vue-virtual-scroller

Show how to implement virtual scrolling in a Vue.js 3 component to render potentially very large lists efficiently.
import { createApp } from 'vue';
import App from './App.vue';
import VueVirtualScroller from 'vue-virtual-scroller';

const app = createApp(App);
app.use(VueVirtualScroller);

app.mount('#app');
First, this piece initializes a Vue application, imports the VueVirtualScroller plugin and registers it within the Vue application to be ready for use in components.
<template>
  <virtual-scroller
    :items="items"
    :item-height="30"
    class="scroller"
    item-tag="div"
  >
    <template v-slot="{ item }">
      <div class="item">
        {{ item.text }}
      </div>
    </template>
  </virtual-scroller>
</template>
This is the template part of a Vue component. It makes use of the <virtual-scroller> tag provided by the vue-virtual-scroller plugin, binding a list of items and specifying the height of each item. It also defines how the items should be displayed by using a scoped slot.
<script setup>
import { ref } from 'vue';

// Example data to be rendered
const items = ref([...Array(10000)].map((_, i) => ({ text: `Item #${i}` })));
</script>
Here, we define the component's script setup block which imports the ref function from Vue. An example dataset is created with a large number of items using the Array.map() method. This is the type of dataset you would use virtual scrolling for.
<style>
.scroller {
  height: 300px;
  overflow-y: auto;
}

.item {
  height: 30px;
  display: flex;
  align-items: center;
  padding: 0 10px;
}
</style>
Lastly, this is the style block of the Vue component, which styles the virtual scroller and the items within it. The scroller is assigned a fixed height and overflow-y to enable scrolling, and each item has a set height matching the item-height property defined in the template.