<template> <div class="container" ref="scrollRef" @scroll="scroll"> <div class="plc" :style="'height: ' + list.length * 60 + 'px;padding-top: ' + paddingTop + 'px'" > <div class="item" v-for="item in renderList" :key="item.id">{{ item.str }}</div> </div> </div> </template> <script setup> const list = ref([]); const paddingTop = ref(0); const renderLen = Math.floor(window.innerHeight / 60); const extraRenderLen = 10; const startIndex = ref(0); const renderList = computed(() => { return list.value.slice( startIndex.value, startIndex.value + renderLen + extraRenderLen * 2 ); }); function initData() { for (let i = 0; i < 10000; i++) { list.value.push({ str: i, id: i, }); } } const scrollRef = ref(); function scroll() { const top = scrollRef.value.scrollTop; // 卷进去了多少条数据 const jump = Math.floor(top / 60); startIndex.value = jump - extraRenderLen > 0 ? jump - extraRenderLen : 0; paddingTop.value = startIndex.value * 60; } initData(); </script> <style lang="scss" scoped> .container { height: 100vh; overflow-y: scroll; .plc { .item { height: 60px; background: pink; border: 4px solid #fff; border-radius: 10px; font-size: 40px; } } } </style>
案例为vue SFC, 使用了 unplugin-auto-import 插件,所以 没有引入 ref computed 等函数
本来想用plc的固定高度撑开 Container 容易, 实现滚动条的自适应计算, 结果设置 overflow-y: scroll 之后, 滚动条直接不显示了
所以, 预计, 只在 item 外面套一个盒子, 也能达到这种 无滚动条 的 虚拟滚动列表 了
如果有什么解决办法, 欢迎提出来!!!
结果如图
标签:vue,const,value,滚动条,startIndex,虚拟,extraRenderLen,滚动,ref From: https://www.cnblogs.com/fmg0224/p/18392349