Open History to see the last commit
1<template>
2 <div>
3 <div>
4 <button @click="rowVirtualizer.scrollToIndex(40)">
5 Scroll to index 40
6 </button>
7 <button @click="rowVirtualizer.scrollToIndex(20)">
8 Then scroll to index 20
9 </button>
10 </div>
11β
12 <br />
13 <br />
14β
15 <div
16 ref="parentRef"
17 class="List"
18 style="height: 200px; width: 400px; overflow: auto"
19 >
20 <table :style="{ height: `${totalSize}px`, width: '100%' }">
21 <thead ref="theadRef">
22 <tr>
23 <th>Index</th>
24 <th>Key</th>
25 </tr>
26 </thead>
27 <tbody>
28 <tr
29 v-for="virtualRow in virtualRows"
30 :key="virtualRow.index"
31 :class="virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'"
32 :style="{
33 position: 'absolute',
34 top: 0,
35 left: 0,
36 width: '100%',
37 height: `${virtualRow.size}px`,
38 transform: `translateY(${virtualRow.start}px)`,
39 }"
40 >
41 <td>#{{ virtualRow.index }}</td>
42 <td>{{ virtualRow.key }}</td>
43 </tr>
44 </tbody>
45 </table>
46 </div>
47 </div>
48</template>
49β
50<script setup lang="ts">
51import { ref, computed } from 'vue'
52import { useElementSize } from '@vueuse/core'
53import { useVirtualizer } from '@tanstack/vue-virtual'
54β
55const parentRef = ref<HTMLElement | null>(null)
56β
57const theadRef = ref<HTMLElement | null>(null)
58β
59const { height } = useElementSize(theadRef)
60β
61const rowVirtualizerOptions = computed(() => {
62 return {
63 count: 10000,
64 getScrollElement: () => parentRef.value,
65 estimateSize: () => 35,
66 overscan: 5,
67 paddingStart: height.value ?? 0,
68 scrollPaddingStart: height.value ?? 0,
69 }
70})
71β
72const rowVirtualizer = useVirtualizer(rowVirtualizerOptions)
73β
74const virtualRows = computed(() => rowVirtualizer.value.getVirtualItems())
75β
76const totalSize = computed(() => rowVirtualizer.value.getTotalSize())
77</script>