詳解vue3中虛擬列表組件的實現(xiàn)
一. 引言
在很多人的博客中看到虛擬列表,一直都沒有好好研究,趁著這次的時間,好好的研究一下了,不知道會不會有人看這篇文章呢?隨便吧哈哈哈,未來希望自己能用得上這篇文章哦。
此篇文章主要實現(xiàn)一下定高的虛擬列表,主要是對虛擬列表的思路做一個簡單的學習了。
二. Vue3虛擬列表組件的實現(xiàn)
2.1 基本思路
關(guān)于虛擬列表的實現(xiàn),以我的角度出發(fā),分為三步:
- 確定截取的數(shù)據(jù)的起始下標,然后根據(jù)起始下標的值計算結(jié)束下標
- 通過padding值填充未渲染位置,使其能夠滑動,同時動態(tài)計算paddingTop和paddingBottom
- 綁定滾動事件,更新截取的視圖列表和padding的值
在這里的話重點在于計算初始的下標,要根據(jù)scrollTop屬性來計算(之前自己曾寫過虛擬列表是根據(jù)滾動的改變多少來改變初始下標的,結(jié)果滾動非??斓臅r候,就完全對應(yīng)不上來了,而通過scrollTop,那么才是穩(wěn)定的,因為scrollTop的值和滾動條的位置綁定,而滾動條的位置和滾動事件觸發(fā)的次數(shù)是沒有唯一性的)
2.2 代碼實現(xiàn)
基本的dom結(jié)構(gòu)
<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>
此處為了保證列表項能夠有更多的自由度,選擇使用插槽,在使用的時候需要確保列表項的高度和設(shè)定的高度一致哦。
計算paddingTop,paddingBottom,visibleItems
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是指滑動區(qū)域的高度,itemHeight是指列表元素的高度,此處為了避免白屏,將end的值設(shè)置為兩個屏幕的大小的數(shù)據(jù),第二個屏幕作為緩沖區(qū);多定義一個renderData變量是因為后面會有下拉加載更多功能,props的值不方便修改(可以使用v-model,但是感覺不需要,畢竟父元素不需要的列表數(shù)據(jù)不需要更新)
綁定滾動事件
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是觸底加載更多函數(shù),在后面代碼中會知道,這里先忽略,在滾動事件中,根據(jù)scrollTop的值計算起始下標satrt,從而更新計算屬性paddingTop,paddingBottom,visibleItems,實現(xiàn)虛擬列表,在這里還使用了請求動畫幀進行節(jié)流優(yōu)化。
三. 完整組件代碼
virtualList.vue
<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: '獲取數(shù)據(jù)失敗,請檢查網(wǎng)絡(luò)后重試', 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
<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
<script setup> import VirtualList from '@/components/virtualList.vue'; import { onMounted, ref } from 'vue'; let listData = ref([]); let num = 200; // 模擬從 API 獲取數(shù)據(jù) const fetchData = async () => { // 這里可以替換成您實際的 API 請求 await new Promise((resolve, reject) => { setTimeout(() => { const newData = Array.from({ length: 200 }, (_, index) => `Item ${index}`); listData.value = newData; resolve(); }, 500); }) } // 加載更多數(shù)據(jù) 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以及錯誤提示,這樣會更加的全面一些,總體上應(yīng)該還是挺滿足很多實際的。
到此這篇關(guān)于詳解vue3中虛擬列表組件的實現(xiàn)的文章就介紹到這了,更多相關(guān)vue3虛擬列表組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue-router 報錯NavigationDuplicated的解決方法
這篇文章主要介紹了Vue-router 報錯NavigationDuplicated的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03elementUI vue this.$confirm 和el-dialog 彈出框 移動 示例demo
這篇文章主要介紹了elementUI vue this.$confirm 和el-dialog 彈出框 移動 示例demo,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07vue-element-admin后臺生成動態(tài)路由及菜單方法詳解
vue-element-admin后臺管理系統(tǒng)模板框架 是vue結(jié)合element-ui一體的管理系統(tǒng)框架,下面這篇文章主要給大家介紹了關(guān)于vue-element-admin后臺生成動態(tài)路由及菜單的相關(guān)資料,需要的朋友可以參考下2023-09-09詳解如何使用router-link對象方式傳遞參數(shù)?
這篇文章主要介紹了如何使用router-link對象方式傳遞參數(shù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05