當后端一次性返回十萬條數據時,前端需要采用多種性能優化策略來避免頁面卡頓。以下是主要的優化方案:
- 分頁加載 - 將數據分批次加載顯示
- 虛擬滾動 - 只渲染可視區域內的數據
- 數據懶加載 - 按需加載數據
- Web Workers - 在后臺線程處理數據
- 時間切片 - 分散渲染任務避免阻塞主線程
下面是具體的實現代碼:
<template><div class="large-data-view"><h2>大數據量處理示例</h2><!-- 性能監控 --><div class="performance-info"><span>總數據量: {{ totalDataCount }}</span><span>當前顯示: {{ startIndex + 1 }} - {{ Math.min(startIndex + pageSize, totalDataCount) }}</span><span>渲染耗時: {{ renderTime }}ms</span></div><!-- 分頁控件 --><div class="pagination-controls"><button @click="prevPage" :disabled="currentPage <= 1">上一頁</button><span>第 {{ currentPage }} 頁,共 {{ totalPages }} 頁</span><button @click="nextPage" :disabled="currentPage >= totalPages">下一頁</button><select v-model="pageSize" @change="onPageSizeChange"><option value="50">每頁50條</option><option value="100">每頁100條</option><option value="200">每頁200條</option><option value="500">每頁500條</option></select></div><!-- 虛擬滾動列表 --><div class="virtual-scroll-container" ref="scrollContainer" @scroll="onScroll"><div class="scroll-placeholder" :style="{ height: totalHeight + 'px' }"></div><div class="visible-items" :style="{ transform: `translateY(${offsetY}px)` }"><div class="data-item" v-for="item in visibleItems" :key="item.id":style="{ height: itemHeight + 'px' }"><span class="item-index">{{ item.id }}</span><span class="item-name">{{ item.name }}</span><span class="item-value">{{ item.value }}</span><span class="item-time">{{ formatTime(item.timestamp) }}</span></div></div></div><!-- 加載指示器 --><div v-if="loading" class="loading-indicator">數據加載中...</div></div>
</template><script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';// 響應式數據
const allData = ref<any[]>([]);
const startIndex = ref(0);
const pageSize = ref(100);
const itemHeight = 50; // 每項高度
const loading = ref(false);
const renderTime = ref(0);
const scrollContainer = ref<HTMLElement | null>(null);// 分頁相關數據
const currentPage = computed(() => Math.floor(startIndex.value / pageSize.value) + 1);
const totalPages = computed(() => Math.ceil(allData.value.length / pageSize.value));
const totalDataCount = computed(() => allData.value.length);// 虛擬滾動相關數據
const visibleCount = ref(15); // 可視區域項目數
const scrollTop = ref(0);
const offsetY = ref(0);
const totalHeight = computed(() => allData.value.length * itemHeight);// 可視區域的數據
const visibleItems = computed(() => {const start = Math.max(0, Math.floor(scrollTop.value / itemHeight));const end = Math.min(allData.value.length, start + visibleCount.value);return allData.value.slice(start, end);
});// 方法
const formatTime = (timestamp: number) => {const date = new Date(timestamp);return date.toLocaleTimeString();
};// 分頁方法
const prevPage = () => {if (currentPage.value > 1) {startIndex.value = (currentPage.value - 2) * pageSize.value;scrollToTop();}
};const nextPage = () => {if (currentPage.value < totalPages.value) {startIndex.value = currentPage.value * pageSize.value;scrollToTop();}
};const onPageSizeChange = () => {startIndex.value = 0;scrollToTop();
};const scrollToTop = () => {if (scrollContainer.value) {scrollContainer.value.scrollTop = 0;}
};// 虛擬滾動處理
const onScroll = () => {if (scrollContainer.value) {scrollTop.value = scrollContainer.value.scrollTop;offsetY.value = Math.floor(scrollTop.value / itemHeight) * itemHeight;}
};// 模擬加載大數據
const loadData = async () => {loading.value = true;const startTime = performance.now();try {// 模擬從后端獲取10萬條數據// 實際項目中這里應該是API調用const data = generateLargeData(100000);allData.value = data;// 使用時間切片技術處理數據渲染await nextTick();const endTime = performance.now();renderTime.value = Math.round(endTime - startTime);} finally {loading.value = false;}
};// 生成模擬數據
const generateLargeData = (count: number) => {const data = [];for (let i = 0; i < count; i++) {data.push({id: i + 1,name: `數據項 ${i + 1}`,value: Math.random() * 1000,timestamp: Date.now() - Math.floor(Math.random() * 10000000)});}return data;
};// 初始化
onMounted(() => {loadData();// 計算可視區域能顯示的項目數if (scrollContainer.value) {visibleCount.value = Math.ceil(scrollContainer.value.clientHeight / itemHeight) + 5;}
});
</script><style scoped>
.large-data-view {height: 100%;display: flex;flex-direction: column;padding: 20px;
}.performance-info {display: flex;gap: 20px;margin-bottom: 20px;padding: 10px;background-color: #f5f5f5;border-radius: 4px;
}.pagination-controls {display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px;padding: 10px;background-color: #f9f9f9;border-radius: 4px;
}.pagination-controls button {padding: 6px 12px;background-color: #007bff;color: white;border: none;border-radius: 4px;cursor: pointer;
}.pagination-controls button:disabled {background-color: #ccc;cursor: not-allowed;
}.pagination-controls select {padding: 6px;border: 1px solid #ddd;border-radius: 4px;
}.virtual-scroll-container {flex: 1;border: 1px solid #ddd;border-radius: 4px;overflow: auto;position: relative;
}.scroll-placeholder {position: absolute;left: 0;top: 0;right: 0;z-index: -1;
}.visible-items {position: absolute;left: 0;right: 0;top: 0;z-index: 1;
}.data-item {display: flex;align-items: center;padding: 0 15px;border-bottom: 1px solid #eee;
}.item-index {width: 80px;font-weight: bold;
}.item-name {flex: 1;
}.item-value {width: 120px;text-align: right;
}.item-time {width: 100px;text-align: right;color: #999;font-size: 0.9em;
}.loading-indicator {position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);padding: 20px;background-color: rgba(0, 0, 0, 0.8);color: white;border-radius: 4px;z-index: 1000;
}
</style>
/*** 大數據處理工具類* 使用Web Workers和時間切片技術處理大量數據*/// 時間切片處理大數據
export class DataProcessor {private chunkSize: number;constructor(chunkSize: number = 1000) {this.chunkSize = chunkSize;}/*** 分塊處理大數據數組* @param data 大數據數組* @param processor 處理函數* @returns Promise*/async processInChunks<T, R>(data: T[], processor: (item: T) => R): Promise<R[]> {const results: R[] = [];const totalChunks = Math.ceil(data.length / this.chunkSize);for (let i = 0; i < totalChunks; i++) {const start = i * this.chunkSize;const end = Math.min(start + this.chunkSize, data.length);const chunk = data.slice(start, end);// 處理當前塊const chunkResults = chunk.map(processor);results.push(...chunkResults);// 讓出控制權,避免阻塞UIif (i < totalChunks - 1) {await this.yieldToMain();}}return results;}/*** 讓出控制權給主線程*/private yieldToMain(): Promise<void> {return new Promise(resolve => {setTimeout(resolve, 0);});}/*** 使用Web Worker處理數據* @param data 數據* @param workerFunction 處理函數字符串* @returns Promise*/processWithWorker<T, R>(data: T[], workerFunction: string): Promise<R[]> {return new Promise((resolve, reject) => {// 創建Web Workerconst workerCode = `self.onmessage = function(e) {const { data, processor } = e.data;const func = new Function('return ' + processor)();const results = data.map(func);self.postMessage(results);};`;const blob = new Blob([workerCode], { type: 'application/javascript' });const worker = new Worker(URL.createObjectURL(blob));worker.onmessage = function(e) {resolve(e.data);worker.terminate();};worker.onerror = function(error) {reject(error);worker.terminate();};worker.postMessage({data,processor: workerFunction});});}
}// 創建數據處理器實例
export const dataProcessor = new DataProcessor(1000);
<template><div class="infinite-scroll-list" ref="container"><div class="list-container"><div class="list-item" v-for="item in displayItems" :key="item.id"><slot :item="item"></slot></div><div v-if="loading" class="loading-more">加載中...</div><div v-if="noMore" class="no-more">沒有更多數據了</div></div></div>
</template><script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';const props = defineProps<{items: any[];pageSize?: number;threshold?: number; // 距離底部多少像素時觸發加載
}>();const emit = defineEmits<{(e: 'loadMore'): void;
}>();// 默認值
const pageSize = props.pageSize || 50;
const threshold = props.threshold || 100;// 響應式數據
const container = ref<HTMLElement | null>(null);
const displayedCount = ref(pageSize);
const loading = ref(false);
const noMore = ref(false);// 計算屬性
const displayItems = computed(() => {return props.items.slice(0, displayedCount.value);
});// 方法
const handleScroll = () => {if (!container.value) return;const { scrollTop, scrollHeight, clientHeight } = container.value;const distanceToBottom = scrollHeight - scrollTop - clientHeight;// 當距離底部小于閾值且還有數據時觸發加載if (distanceToBottom < threshold && !loading && !noMore.value) {loadMore();}
};const loadMore = () => {if (displayedCount.value >= props.items.length) {noMore.value = true;return;}loading.value = true;// 模擬異步加載setTimeout(() => {displayedCount.value = Math.min(displayedCount.value + pageSize,props.items.length);loading.value = false;if (displayedCount.value >= props.items.length) {noMore.value = true;}}, 300);
};// 暴露方法給父組件
defineExpose({reset() {displayedCount.value = pageSize;noMore.value = false;},setLoading(status: boolean) {loading.value = status;}
});// 生命周期
onMounted(() => {if (container.value) {container.value.addEventListener('scroll', handleScroll);}
});onBeforeUnmount(() => {if (container.value) {container.value.removeEventListener('scroll', handleScroll);}
});
</script><style scoped>
.infinite-scroll-list {height: 100%;overflow-y: auto;
}.list-item {padding: 10px;border-bottom: 1px solid #eee;
}.loading-more,
.no-more {padding: 15px;text-align: center;color: #999;
}
</style>
這些優化方案可以有效解決前端處理大量數據時的卡頓問題:
- 分頁加載:將10萬條數據分頁顯示,每次只渲染少量數據
- 虛擬滾動:只渲染可視區域內的數據項,大幅減少DOM節點數量
- 時間切片:將大數據處理任務分解成小塊,避免長時間阻塞主線程
- 按需渲染:根據用戶滾動位置動態加載和卸載數據
- 性能監控:實時顯示渲染性能指標,便于調優
通過這些技術的組合使用,即使面對10萬條數據,頁面也能保持流暢的用戶體驗。