企業(yè)做網(wǎng)站需要花多少錢搜索引擎seo關(guān)鍵詞優(yōu)化效果
虛擬列表 - Vue3實現(xiàn)一個可動態(tài)改變高度的虛擬滾動列表
前言
在開發(fā)中經(jīng)常遇到大量的渲染列表數(shù)據(jù)問題,往往我們就只是簡單地遍歷渲染,沒有過多地去關(guān)注是否會存在性能問題,這導(dǎo)致如果數(shù)據(jù)量較大的時候,比如上萬條數(shù)據(jù),將會在dom中渲染上萬個節(jié)點,這將加大瀏覽器的開銷,可能會導(dǎo)致頁面卡頓,加載慢等性能問題。因此,在渲染大量數(shù)據(jù)時,可以選擇使用虛擬列表,只渲染用戶可視區(qū)域內(nèi)的dom節(jié)點。該組件已開源上傳npm,可以直接安裝使用,Git地址在文尾。
虛擬列表實現(xiàn)原理
每條固定高度
1、通過傳入組件的每條數(shù)據(jù)的高度,計算整個列表的高度,從而得到滾動列表的總高,并將總高賦值給列表。
2、監(jiān)聽滾動事件,監(jiān)聽外層容器的滾動事件,并確定可視區(qū)域內(nèi)起止數(shù)據(jù)在總數(shù)據(jù)的索引值,這可以通過scrollTop來實現(xiàn)。
3、設(shè)置數(shù)據(jù)對應(yīng)的元素,為每條數(shù)據(jù)設(shè)置一個絕對定位,其中top等于索引值乘以每條數(shù)據(jù)的高度。
4、考慮緩沖條數(shù),為了避免滑動過快產(chǎn)生空白,可以設(shè)置緩沖條數(shù)。具體來說,如果滾動到底部,可以只顯示最后N條數(shù)據(jù),如果滾動到上部,可以只顯示前N條數(shù)據(jù)。
這樣,就可以實現(xiàn)一個固定高度的虛擬列表。
每條動態(tài)高度
原理和固定高度基本一致,差別在于,用戶可以預(yù)先定義每條數(shù)據(jù)的高度,在渲染時再動態(tài)獲取每一條數(shù)據(jù)的實際高度,從而重新計算滾動列表的總體高度。
主要代碼實現(xiàn)
模板部分
showItemList
循環(huán)可視區(qū)域內(nèi)的數(shù)據(jù)+緩存區(qū)的數(shù)據(jù)
<template><div class="virtual-wrap" ref="virtualWrap" :style="{width: width + 'px',height: height + 'px',}" @scroll="scrollHandle"><div class="virtual-content" :style="{height: totalEstimatedHeight +'px'}"><list-item v-for="(item,index) in showItemList" :key="item.dataIndex+index" :index="item.dataIndex" :data="item.data" :style="item.style"@onSizeChange="sizeChangeHandle"><template #slot-scope="slotProps"><slot name="slot-scope" :slotProps="slotProps"></slot></template></list-item></div></div>
</template>
獲取需要渲染的數(shù)據(jù)
通過可視區(qū)域內(nèi)的開始和結(jié)束索引,獲取需要渲染的列表數(shù)據(jù)。
const getCurrentChildren = () => {//重新計算高度estimatedHeight(props.itemEstimatedSize,props.itemCount)const [startIndex, endIndex] = getRangeToRender(props, scrollOffset.value)const items = [];for (let i = startIndex; i <= endIndex; i++) {const item = getItemMetaData(i);const itemStyle = {position: 'absolute',height: item.size + 'px',width: '100%',top: item.offset + 'px',};items.push({style: itemStyle,data: props.data[i],dataIndex:i});}showItemList.value = items;
}
獲取開始和結(jié)束索引
const getRangeToRender = (props: any, scrollOffset: any) => {const { itemCount } = props;const startIndex = getStartIndex(props, scrollOffset);const endIndex = getEndIndex(props, startIndex + props.buffCount);return [Math.max(0, startIndex -1),Math.min(itemCount - 1, endIndex ),];
};const getStartIndex = (props: any, scrollOffset: number) => {const { itemCount } = props;let index = 0;while (true) {const currentOffset = getItemMetaData(index).offset;if (currentOffset >= scrollOffset) return index;if (index >= itemCount) return itemCount;index++}
}const getEndIndex = (props: any, startIndex: number) => {const { height, itemCount } = props;// 獲取可視區(qū)內(nèi)開始的項const startItem = getItemMetaData(startIndex);// 可視區(qū)內(nèi)最大的offset值const maxOffset = Number(startItem.offset) + Number(height);// 開始項的下一項的offset,之后不斷累加此offset,知道等于或超過最大offset,就是找到結(jié)束索引了let offset = Number(startItem.offset) + startItem.size;// 結(jié)束索引let endIndex = startIndex;// 累加offsetwhile (offset <= maxOffset && endIndex < (itemCount - 1)) {endIndex++;const currentItem = getItemMetaData(endIndex);offset += currentItem.size;}// 更新已計算的項的索引值measuredData.lastMeasuredItemIndex = endIndex;return endIndex;
};
動態(tài)計算節(jié)點高度
const estimatedHeight = (defaultEstimatedItemSize = 50, itemCount: number) => {let measuredHeight = 0;const { measuredDataMap, lastMeasuredItemIndex } = measuredData;// 計算已經(jīng)獲取過真實高度的項的高度之和if (lastMeasuredItemIndex >= 0) {const lastMeasuredItem = measuredDataMap[lastMeasuredItemIndex];measuredHeight = lastMeasuredItem.offset + lastMeasuredItem.size;}// 未計算過真實高度的項數(shù)const unMeasuredItemsCount = itemCount - measuredData.lastMeasuredItemIndex - 1;// 預(yù)測總高度totalEstimatedHeight.value = measuredHeight + unMeasuredItemsCount * defaultEstimatedItemSize;
}
子組件實現(xiàn)
1、通過ResizeObserver
在子節(jié)點高度變化時觸發(fā)父組件的方法,重新計算整體高度。
2、通過插槽將每條數(shù)據(jù)動態(tài)插入到列表中。
<template><div :style="style" ref="domRef"><slot name="slot-scope" :data="data"></slot></div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'const emit = defineEmits(['onSizeChange']);const props = defineProps({style: {type: Object,default: () => { }},data: {type: Object,default: () => { }},index: {type: Number,default: 0}
})const domRef = ref<any>(null);
const resizeObserver:any = null;onMounted(() => {const domNode = domRef.value.children[0];emit("onSizeChange", props.index, domNode);const resizeObserver = new ResizeObserver(() => {emit("onSizeChange", props.index, domNode);});resizeObserver.observe(domNode);
})onUnmounted(() => {if (resizeObserver) {resizeObserver?.unobserve(domRef.value.children[0]);}
})
</script>
組件使用
npm install @fcli/vue-virtually-list --save-dev 來安裝在項目中使用
import VueVirtuallyList from '@fcli/vue-virtually-list';
const app=createApp(App)
app.use(VueVirtuallyList);
示例:
<div class="content"><vue-virtually-list :data="list" :height="400" :width="600" :itemCount="1000" :itemEstimatedSize="20" :buffCount="50"><template #slot-scope="{slotProps}"><div class="li">{{ slotProps.data.text }}</div></template></vue-virtually-list>
</div>
屬性 | 屬性名稱 | 類型 | 可選值 |
---|---|---|---|
data | 列表數(shù)據(jù) | Array | [] |
height | 虛擬容器的高度 | number | 0 |
width | 虛擬容器的寬度 | number | 0 |
itemCount | 滾動列表的條數(shù) | number | 0 |
itemEstimatedSize | 預(yù)設(shè)每行數(shù)據(jù)的高度 | number | 可不填,組件會動態(tài)計算 |
buffCount | 上下緩沖區(qū)的條數(shù) | number | 增加快速滾動時的流暢性 |
#slot-scope | 插槽 | object | slotProps.data| |
slot
例:
<template #slot-scope="{slotProps}"><div class="li">{{ slotProps.data.text }}</div></template>
Git地址:https://gitee.com/fcli/vue-virtually-list.git