数据分批加载(大量数据,el-table表格不分页)

488 阅读1分钟

数据分批加载(大量数据,el-table表格不分页)


需求

  1. 不分页展示表格数据,解决前端渲染太慢的问题
  2. 滑动加载数据

实现

1. 表格渲染

  1. 数据变量

    /* 滚动加载 */
    const visibleData = ref([]); // 存放当前可见数据,滚动时逐步加载新数据
    const batchSize = ref(20); // 每次加载的数据量
    const startIndex = ref(0); // 当前数据的起始索引
    const tableData = ref([]); // 请求回来的数据
    
  2. 数据渲染

    <el-table :data="visibleData" >
    	<el-table-column type="index" label="序号" ></el-table-column>
    </el-table>
    

2. 数据加载

  1. 挂载后请求数据,并首次加载第一批数据;同时监听页面滚动事件

    const getTableData = () => {
    	// reqData数据请求
    	reqData().then((response) => {
    		tableData.value = response;
    		// 每次请求后重置数据
    		startIndex.value = 0;
    		visibleData.value = [];
    		if (tableData.value) {
    			loadNextBatch(); // 加载第一批数据
    		}
    	});
    };
    // 
    onMounted(async () => {
    	try {
    		getTableData();
    		window.addEventListener("scroll", handleScroll);
    	} catch (error) {
    		console.log(error);
    	}
    });
    onUnmounted(() => {
    	window.removeEventListener("scroll", handleScroll);
    });
    
  2. 加载数据

    const loadNextBatch = () => {
    	// 每次新加载batchSize条数据
    	const endIndex = Math.min(
    		startIndex.value + batchSize.value,
    		tableData.value.length
    	);
        // 在原来的基础上增加数据
    	visibleData.value = [
    		...visibleData.value,
    		...tableData.value.slice(startIndex.value, endIndex),
    	];
        // 下一批次起始点
    	startIndex.value = endIndex;
    };
    

3. 滚动监听

  1. 监听滚动事件,根据滚动位置(快到底)加载更多数据

    const handleScroll = () => {
    	const windowHeight = window.innerHeight;
    	const documentHeight = document.documentElement.scrollHeight;
    	const scrollTop = window.scrollY;
        
    	if (windowHeight + scrollTop >= documentHeight - 200) {
    		loadNextBatch(); // 当滚动到页面底部时加载下一批数据 
    	}
    };
    

4. 其他

  1. 其他方式

    • 和后端配合分批请求,和分页差不多
    • 可视区(虚拟滚动),每次仅渲染[start, end)的数据。还得自己写滚动条(记得当时尝试的有点问题,一卡一卡的。想用个滚动条的插件,最后觉得更麻烦)。
  2. 感觉不难但当时花了挺久时间,还是需要在写之前先想想清楚。