Open History to see the last commit
1<template>
2 <div>
3 <button @click="rowVirtualizer.scrollToIndex(0)">scroll to the top</button>
4 <span style="padding: 0 4px"></span>
5 <button @click="rowVirtualizer.scrollToIndex(sentences.length / 2)">
6 scroll to the middle
7 </button>
8 <span style="padding: 0 4px"></span>
9 <button @click="rowVirtualizer.scrollToIndex(sentences.length - 1)">
10 scroll to the end
11 </button>
12 <hr />
13 <div
14 ref="parentRef"
15 class="List"
16 style="height: 400px; width: 400px; overflow-y: auto; contain: strict"
17 >
18 <div
19 :style="{
20 height: `${totalSize}px`,
21 width: '100%',
22 position: 'relative',
23 }"
24 >
25 <div
26 :style="{
27 position: 'absolute',
28 top: 0,
29 left: 0,
30 width: '100%',
31 transform: `translateY(${virtualRows[0]?.start ?? 0}px)`,
32 }"
33 >
34 <div
35 v-for="virtualRow in virtualRows"
36 :key="virtualRow.key"
37 :data-index="virtualRow.index"
38 :ref="measureElement"
39 :class="virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'"
40 >
41 <div style="padding: 10px 0">
42 <div>Row {{ virtualRow.index }}</div>
43 <div>{{ sentences[virtualRow.index] }}</div>
44 </div>
45 </div>
46 </div>
47 </div>
48 </div>
49 </div>
50</template>
51β
52<script setup lang="ts">
53import { ref, computed } from 'vue'
54import { useVirtualizer } from '@tanstack/vue-virtual'
55import { generateSentences } from './utils'
56β
57const sentences = generateSentences()
58β
59const parentRef = ref<HTMLElement | null>(null)
60β
61const rowVirtualizer = useVirtualizer({
62 count: sentences.length,
63 getScrollElement: () => parentRef.value,
64 estimateSize: () => 55,
65})
66β
67const virtualRows = computed(() => rowVirtualizer.value.getVirtualItems())
68β
69const totalSize = computed(() => rowVirtualizer.value.getTotalSize())
70β
71const measureElement = (el) => {
72 if (!el) {
73 return
74 }
75β
76 rowVirtualizer.value.measureElement(el)
77β
78 return undefined
79}
80</script>