前言
针对表格展示数据,用户提出要求前端在表格下面有一展示多少条数据的选项,如果要求一次性展示10000条数据,如果直接染会造成页面的卡顿,渲染速度下降,内容展示慢,如果有操作,操作会卡顿
下面总结常见的几种大数据渲染方案
虚拟列表渲染
用虚拟列表的手段,即先对设置的可见区域内的数据进行演染,然后计算出鼠标滚动距离大约是滚动了多少项,通过动态的设置距离顶部的top值达到可见区域动态染数据不会卡顿的效果
<template>
<!-- 虚拟列表容器 -->
<div
class="virtualListWrap"
ref="virtualListWrap"
:style="{ height: itemHeight * count + 'px' }"
@scroll="handleScroll"
>
<!-- 占位元素,高度为所有数据的总高度 -->
<div
class="placeholderDom"
:style="{ height: allListData.length * itemHeight + 'px' }"
>
</div>
<!-- 实际显示的内容区域 -->
<div class="contentList" :style="{ top: topVal }">
<!-- 循环渲染可见的数据项 -->
<div
v-for="(item, index) in showListData"
:key="index"
class="itemClass"
:style="{ height: itemHeight + 'px' }"
>
{
{
item.name }}
</div>
</div>
<!-- 加载提示 -->
<div class="loadingBox" v-show="loading">
<i class="el-icon-loading"></i>
<span>loading...</span>
</div>
</div>
</template>
<script setup>
import {
ref, computed, onMounted } from 'vue';
import axios from "axios";
const allListData = ref([]); // 存储所有数据的数组
const itemHeight = 40; // 每个列表项的高度(像素)
const count = 10; // 一次显示的数据项数量
const start = ref(0); // 当前可见区域的起始索引
const end = ref(10); // 当前可见区域的结束索引
const topVal = ref('0px'); // 内容区域的顶部偏移量
const loading = ref(false); // 控制加载提示的显示
const virtualListWrap = ref(null);
// 计算当前应该显示的数据
const showListData = computed(() => {
return allListData.value.slice(start.value