<template>
<div ref="listRef" class="infinite-list-container" @scroll="scrollEvent($event)">
<div :style="{ height: listHeight + 'px' }" class="infinite-list-phantom"></div>
<div :style="{ transform: getTransform }" class="infinite-list">
<div v-for="item in visibleData" :key="item.id" ref="items"
:style="{ height: itemSize + 'px', backgroundColor: item.color }"
class="infinite-list-item">
{{ item.value }} - {{ item.color }}
</div>
</div>
</div>
</template>
<script setup>
import {onMounted} from "vue";
let listRef = $ref()
let listData = $ref([])
let itemSize = $ref(120)
let screenHeight = $ref(0)
let startOffset = $ref(0)
let start = $ref(0)
let end = $ref(null)
let listHeight = $computed(() => {
return listData.length * itemSize;
})
let visibleCount = $computed(() => {
return Math.ceil(screenHeight / itemSize)
})
let getTransform = $computed(() => {
return `translate3d(0,${startOffset}px,0)`;
})
let visibleData = $computed(() => {
return listData.slice(start, Math.min(end, listData.length));
})
function scrollEvent() {
let scrollTop = listRef.scrollTop;
start = Math.floor(scrollTop / itemSize);
end = start + visibleCount;
startOffset = scrollTop - (scrollTop % itemSize);
}
function randomColor(alpha) {
alpha = alpha == undefined ? (Math.random() * 10 / 10).toFixed(1) : alpha;
alpha = Number(alpha);
if (isNaN(alpha)) alpha = 1;
let col = "rgba(";
for (let i = 0; i < 3; i++) {
col += ~~(Math.random() * 256) + ",";
}
col += alpha + ")";
return col;
}
onMounted(() => {
screenHeight = document.documentElement.clientHeight;
start = 0;
end = start + visibleCount;
for (let i = 0; i < 100000; i++) {
listData.push({
id: i,
value: i,
color: randomColor()
});
}
})
</script>
.infinite-list-container {
height: calc(100vh - 55px);
overflow: auto;
position: relative;
-webkit-overflow-scrolling: touch;
}
.infinite-list-phantom {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: -1;
}
.infinite-list {
left: 0;
right: 0;
top: 0;
position: absolute;
text-align: center;
}
.infinite-list-item {
padding: 10px;
color: #555;
box-sizing: border-box;
border-bottom: 1px solid #999;
display: flex;
align-items: center;
justify-content: center;
}