Installation
This page adds the package to your project and renders a grid of 1,000 items. Install the package first.
pnpm add vvirtual-grid
npm install vvirtual-grid
bun add vvirtual-grid
Use it in Vue
Import VirtualGrid in the component that renders it, and create a page provider from your items.
<script setup>
import { VirtualGrid, createPageProvider } from "vvirtual-grid/vue";
const items = Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `Item ${i}` }));
const pageProvider = createPageProvider(items);
</script>
The grid reads its scroll position from the nearest ancestor that scrolls, so put it inside an element with overflow-y: auto and a fixed height. Put both on that element, not on <VirtualGrid>. The VirtualGrid reference explains why.
<template>
<div class="h-96 overflow-y-auto">
<VirtualGrid
:length="items.length"
:page-size="40"
:page-provider="pageProvider"
class="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-4"
>
<template #default="{ item, style }">
<div :style="style" class="h-24">{{ item.name }}</div>
</template>
<template #probe>
<div class="h-24" />
</template>
</VirtualGrid>
</div>
</template>
The grid is a CSS grid, so give it display: grid and column tracks. Bind style on the root element of each item, because it carries the item's position. The probe slot holds an empty element with the same height as an item, which the grid measures to learn the item size. Sizing and direction explains the probe.
display: grid, column tracks, and a height with overflow-y: auto on the scroll container. Use your own CSS for those if you do not use Tailwind.To use <VirtualGrid> in every component without an import, register the plugin once.
import { createApp } from "vue";
import { VVirtualGridPlugin } from "vvirtual-grid/vue";
import App from "./App.vue";
createApp(App).use(VVirtualGridPlugin).mount("#app");
Use it in Nuxt
Add the module to nuxt.config.ts.
export default defineNuxtConfig({
modules: ["vvirtual-grid/nuxt"],
});
The module auto-imports <VirtualGrid> and useVirtualGridProvider, which is createPageProvider under a Nuxt name. Use them in a page without importing anything.
<script setup>
const items = Array.from({ length: 1000 }, (_, i) => ({ id: i, name: `Item ${i}` }));
const pageProvider = useVirtualGridProvider(items);
</script>
The template is the same as in Use it in Vue.
vvirtual-grid/primitives in the files that use them.Check that it works
Scroll the container. Open your browser's Elements panel and count the children of the grid. The count stays in the dozens while the item numbers keep changing.