JavaScript Vue

Create a Virtual Scrolling List with vue-virtual-scroll-list

Spread the love

To increase scrolling performance when scrolling big lists, we have to use the use virtual scrolling to only show the items that are being scrolled.

To make this task easy, we can use the vue-virtual-scroll-list to create a virtual scroll list.

To install it, we run:

npm install vue-virtual-scroll-list --save

Then we use it by creating a component to display the entries.

We do that by creating Item.vue in the components folder:

  <div>{{ index }} - {{ source.num }}</div>

export default {
  name: "Item",
  props: {
    index: Number,
    source: Object

It takes the index prop for the index, and the source prop, which is an array entry object that we want to display.

The object should have a unique ID and other properties that display.

Next, we create a parent component that uses the virtual-list component that comes with the package.

In App.vue, we add:

  <div id="app">
      style="height: 360px; overflow-y: auto;"

import Item from "./components/Item";
import VirtualList from "vue-virtual-scroll-list";

export default {
  name: "App",
  components: { "virtual-list": VirtualList },
  data() {
    return {
      itemComponent: Item,
      nums: Array(1000)
        .map((_, i) => ({ uid: i.toString(), num: Math.random() }))

We set the itemComponent state to the Item component we just created.

Also, we register the 'virtual-list' component that we imported rom the vue-virtual-scroll-list package.

The data we display are in the nums folder, which is an array with 1000 entries that has a bunch of random numbers in it.

Then in the template, we style our virtual scroll list.

The data-key should the property name of the array entry that has the unique ID in it.

In this example, it would be the uid field.

num is the property of the field that we display, which would be passed to the source prop, so we use source.num to access the data.

data-sources is the data source that we want to display, which is nums in our example.

data-component should be set to the component that we used to render the rows.

In this case, it’s the Item component.

We set the height of the list to 360px and enable overflow in the vertical direction so that we can scroll.

Now we have a list with lots of numbers than we can scroll up and down quickly because of virtual scrolling.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *