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