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