Categories
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:

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

<script>
export default {
  name: "Item",
  props: {
    index: Number,
    source: Object
  }
};
</script>

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:

<template>
  <div id="app">
    <virtual-list
      style="height: 360px; overflow-y: auto;"
      data-key="uid"
      :data-sources="nums"
      :data-component="itemComponent"
    />
  </div>
</template>

<script>
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)
        .fill()
        .map((_, i) => ({ uid: i.toString(), num: Math.random() }))
    };
  }
};
</script>

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 *