Create a simple virtual scroller (renders only visible items).
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
<template>
<div class="viewport" @scroll="onScroll" :style="{ height: viewportHeight + 'px', overflowY: 'auto' }">
<div :style="{ height: totalHeight + 'px', position: 'relative' }">
<div v-for="item in visibleItems" :key="item.id" :style="{ top: item.top + 'px', position: 'absolute', height: itemHeight + 'px' }">
{{ item.text }}
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const props = defineProps({ items: Array, itemHeight: Number, viewportHeight: Number });
const scrollTop = ref(0);
const totalHeight = computed(() => props.items.length * props.itemHeight);
const startIndex = computed(() => Math.floor(scrollTop.value / props.itemHeight));
const endIndex = computed(() => Math.min(props.items.length, startIndex.value + Math.ceil(props.viewportHeight / props.itemHeight)));
const visibleItems = computed(() => {
return props.items.slice(startIndex.value, endIndex.value + 1).map((item, i) => ({
...item,
top: (startIndex.value + i) * props.itemHeight
}));
});
const onScroll = (e) => scrollTop.value = e.target.scrollTop;
</script>