一. 引言
在很多人的博客中看到虚拟列表,一直都没有好好研究,趁着这次的时间,好好的研究一下了,不知道会不会有人看这篇文章呢?随便吧哈哈哈,未来希望自己能用得上这篇文章哦。
此篇文章主要实现一下定高的虚拟列表,主要是对虚拟列表的思路做一个简单的学习了。
二. Vue3虚拟列表组件的实现
2.1 基本思路
关于虚拟列表的实现,以我的角度出发,分为三步:
- 确定截取的数据的起始下标,然后根据起始下标的值计算结束下标
- 通过padding值填充未渲染位置,使其能够滑动,同时动态计算paddingTop和paddingBottom
- 绑定滚动事件,更新截取的视图列表和padding的值
在这里的话重点在于计算初始的下标,要根据scrollTop属性来计算(之前自己曾写过虚拟列表是根据滚动的改变多少来改变初始下标的,结果滚动非常快的时候,就完全对应不上来了,而通过scrollTop,那么才是稳定的,因为scrollTop的值和滚动条的位置绑定,而滚动条的位置和滚动事件触发的次数是没有唯一性的)
2.2 代码实现
- 基本的dom结构
html
<template>
<div class="scroll-box" ref="scrollBox" @scroll="handleScroll"
:style="{ height: scrollHeight + 'px' }">
<div class="virtual-list" :style="{ paddingTop: paddingTop + 'px', paddingBottom: paddingBottom + 'px' }">
<div v-for="(item, index) in visibleItems" :key="index" :style="{ height: itemHeight + 'px' }">
<slot name="item" :item="item" :index="index"></slot>
</div>
</div>
<Loading :is-show="isShowLoad" />
</div>
</template>
此处为了保证列表项能够有更多的自由度,选择使用插槽,在使用的时候需要确保列表项的高度和设定的高度一致哦。
- 计算paddingTop,paddingBottom,visibleItems
js
const visibleCount = Math.ceil(props.scrollHeight / props.itemHeight) + 1
const start = ref(0)
const end = computed(() => Math.min(start.value + 2 * visibleCount - 1,renderData.value.length))
const paddingTop = computed(() => start.value * props.itemHeight)
const renderData = ref([...props.listData])
const paddingBottom = computed(() => (renderData.value.length - end.value) * props.itemHeight)
const visibleItems = computed(() => renderData.value.slice(start.value, end.value))
其中scrollHeight是指滑动区域的高度,itemHeight是指列表元素的高度,此处为了避免白屏,将end的值设置为两个屏幕的大小的数据,第二个屏幕作为缓冲区;多定义一个renderData变量是因为后面会有下拉加载更多功能,props的值不方便修改(可以使用v-model,但是感觉不需要,毕竟父元素不需要的列表数据不需要更新)
- 绑定滚动事件
js
let lastIndex = start.value;
const handleScroll = rafThrottle(() => {
onScrollToBottom();
onScrolling();
});
const onScrolling = () => {
const scrollTop = scrollBox.value.scrollTop;
let thisStartIndex = Math.floor(scrollTop / props.itemHeight);
const isSomeStart = thisStartIndex == lastIndex;
if (isSomeStart) return;
const isEndIndexOverListLen = thisStartIndex + 2 * visibleCount - 1 >= renderData.value.length;
if (isEndIndexOverListLen) {
thisStartIndex = renderData.value.length - (2 * visibleCount - 1);
}
lastIndex = thisStartIndex;
start.value = thisStartIndex;
}
function rafThrottle(fn) {
let lock = false;
return function (...args) {
if (lock) return;
lock = true;
window.requestAnimationFrame(() => {
fn.apply(args);
lock = false;
});
};
}
其中onScrollToBottom是触底加载更多函数,在后面代码中会知道,这里先忽略,在滚动事件中,根据scrollTop的值计算起始下标satrt,从而更新计算属性paddingTop,paddingBottom,visibleItems,实现虚拟列表,在这里还使用了请求动画帧进行节流优化。
四. 完整组件代码
- virtualList.vue
js
<template>
<div class="scroll-box" ref="scrollBox" @scroll="handleScroll"
:style="{ height: scrollHeight + 'px' }">
<div class="virtual-list" :style="{ paddingTop: paddingTop + 'px', paddingBottom: paddingBottom + 'px' }">
<div v-for="(item, index) in visibleItems" :key="index" :style="{ height: itemHeight + 'px' }">
<slot name="item" :item="item" :index="index"></slot>
</div>
</div>
<Loading :is-show="isShowLoad" />
</div>
</template>
<script setup>
import { ref, computed,onMounted,onUnmounted } from 'vue'
import Loading from './Loading.vue';
import { ElMessage } from 'element-plus'
const props = defineProps({
listData: { type: Array, default: () => [] },
itemHeight: { type: Number, default: 50 },
scrollHeight: { type: Number, default: 300 },
loadMore: { type: Function, required: true }
})
const isShowLoad = ref(false);
const visibleCount = Math.ceil(props.scrollHeight / props.itemHeight) + 1
const start = ref(0)
const end = computed(() => Math.min(start.value + 2 * visibleCount - 1,renderData.value.length))
const paddingTop = computed(() => start.value * props.itemHeight)
const renderData = ref([...props.listData])
const paddingBottom = computed(() => (renderData.value.length - end.value) * props.itemHeight)
const visibleItems = computed(() => renderData.value.slice(start.value, end.value))
const scrollBox = ref(null);
let lastIndex = start.value;
const handleScroll = rafThrottle(() => {
onScrollToBottom();
onScrolling();
});
const onScrolling = () => {
const scrollTop = scrollBox.value.scrollTop;
let thisStartIndex = Math.floor(scrollTop / props.itemHeight);
const isSomeStart = thisStartIndex == lastIndex;
if (isSomeStart) return;
const isEndIndexOverListLen = thisStartIndex + 2 * visibleCount - 1 >= renderData.value.length;
if (isEndIndexOverListLen) {
thisStartIndex = renderData.value.length - (2 * visibleCount - 1);
}
lastIndex = thisStartIndex;
start.value = thisStartIndex;
}
const onScrollToBottom = () => {
const scrollTop = scrollBox.value.scrollTop;
const clientHeight = scrollBox.value.clientHeight;
const scrollHeight = scrollBox.value.scrollHeight;
if (scrollTop + clientHeight >= scrollHeight) {
loadMore();
}
}
let loadingLock = false;
let lockLoadMoreByHideLoading_once = false;
const loadMore = (async () => {
if (loadingLock) return;
if (lockLoadMoreByHideLoading_once) {
lockLoadMoreByHideLoading_once = false;
return;
}
loadingLock = true;
isShowLoad.value = true;
const moreData = await props.loadMore().catch(err => {
console.error(err);
ElMessage({
message: '获取数据失败,请检查网络后重试',
type: 'error',
})
return []
})
if (moreData.length != 0) {
renderData.value = [...renderData.value, ...moreData];
handleScroll();
}
isShowLoad.value = false;
lockLoadMoreByHideLoading_once = true;
loadingLock = false;
})
function rafThrottle(fn) {
let lock = false;
return function (...args) {
if (lock) return;
lock = true;
window.requestAnimationFrame(() => {
fn.apply(args);
lock = false;
});
};
}
onMounted(() => {
scrollBox.value.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
scrollBox.value.removeEventListener('scroll', handleScroll);
});
</script>
<style scoped>
.virtual-list {
position: relative;
}
.scroll-box {
overflow-y: auto;
}
</style>
- Loading.vue
js
<template>
<div class="loading" v-show="pros.isShow">
<p>Loading...</p>
</div>
</template>
<script setup>
const pros = defineProps(['isShow'])
</script>
<style>
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 50px;
background-color: #f5f5f5;
}
</style>
以下是使用demo App.vue
js
<script setup>
import VirtualList from '@/components/virtualList.vue';
import { onMounted, ref } from 'vue';
let listData = ref([]);
let num = 200;
// 模拟从 API 获取数据
const fetchData = async () => {
// 这里可以替换成您实际的 API 请求
await new Promise((resolve, reject) => {
setTimeout(() => {
const newData = Array.from({ length: 200 }, (_, index) => `Item ${index}`);
listData.value = newData;
resolve();
}, 500);
})
}
// 加载更多数据
const loadMore = () => {
// 这里可以替换成您实际的 API 请求
return new Promise((resolve) => {
setTimeout(() => {
const moreData = Array.from({ length: 30 }, (_, index) => `Item ${num + index}`);
num += 30;
resolve(moreData);
}, 500);
});
//模拟请求错误
// return new Promise((_, reject) => {
// setTimeout(() => {
// reject('错误模拟');
// }, 1000);
// })
}
onMounted(() => {
fetchData();
});
</script>
<template>
<!-- class="virtualContainer" -->
<VirtualList v-if="listData.length > 0"
:listData="listData" :itemHeight="50" :scrollHeight="600" :loadMore="loadMore">
<template #item="{ item,index }">
<div class="list-item">
{{ item }}
</div>
</template>
</VirtualList>
</template>
<style scoped>
.list-item {
height: 50px;
line-height: 50px;
border-bottom: 1px solid #ccc;
text-align: center;
}
</style>
此处添加了常用的加载更多和loading以及错误提示,这样会更加的全面一些,总体上应该还是挺满足很多实际的?如果你看了我的文章,觉得还可以,但是还是和自己的需求出入有些大,欢迎批评指正!!!