前端加载,渲染十万条数据(性能优化)

1.场景

项目中某个弹窗展示设备信息卡片,返回的设备信息很多,页面样式有很花哨,导致渲染极其缓慢
f12,查看性能,这里可以看到页面加载在哪一步分耗时最长,针对性进行优化(图为举例)
在这里插入图片描述

2.解决思路

采用虚拟列表的方式,滚动时,dom元素数量不变,只改变展示的数据
结构描述:
父盒子A,添加滚动事件
子盒子B,用于模拟滚动条长度,高度设为单条展示信息盒子的高度×子盒子的数量
子盒子C,信息展示的载体,里面是一定数量的单条展示信息盒子,子盒子C相对于父盒子A绝对定位,每次滚动时修改偏移量,保证信息显示在父盒子A的视口,不随滚动卷到其他地方

3.代码演示

<template>
  <div class="container">
    <div class="showWinsow" ref="showWinsow" :style="{ '--rowHeight': rowHeight + 'px' }" @scroll="scrollEvent">
      <!-- 子元素超出父元素的高度 -->
      <div class="scrollBox" ref="scrollBox"></div>
      <!-- 数据列表 -->
      <div class="itemBox" ref="itemBox">
        <div class="item" v-for="item in showList" :key="item">
          {{ item.n }}</div>
      </div>
    </div>
  </div>
</template>
<script>
const propsData_bigList = new Array(100000).fill(null).map((e, i) => ({ n: (i + 1) }))//模拟传入本组件的超大数据
export default {
  data() {
    return {
      list: Object.freeze(propsData_bigList),//冻结数据,优化性能,//接收传入本组件的超大数据
      offsetValue: '',//滚动的距离
      startIndex: 0,//列表展示的开始索引
      endIndex: 20,//列表展示的结束索引
      viewCount: 20,//传入的行数
      rowHeight: 20//传入的行高
    }
  },
  created() {
  },
  mounted() {
    this.$refs.showWinsow.style.height = (this.viewCount * this.rowHeight) + 'px'
    this.$refs.scrollBox.style.height = (this.rowHeight * this.list.length) + 'px'
  },
  computed: {
    showList() {
      return this.list.slice(this.startIndex, this.endIndex)
    }
  },
  methods: {
    //滚动处理逻辑
    scrollEvent() {
      this.offsetValue = Math.round(this.$refs.showWinsow.scrollTop)
      console.log(this.offsetValue, '当前滚动偏移值');
      this.startIndex = Math.round(this.offsetValue / this.rowHeight)
      this.endIndex = this.startIndex + this.viewCount
      this.$refs.itemBox.style.transform = `translateY(${this.offsetValue}px)`
    }
  }
}
</script>
<style scoped>
.container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.showWinsow {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
  overflow-y: auto;
  background-color: skyblue;
  border: 1px solid red;
}

.scrollBox {}

.itemBox {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}

.item {
  height: var(--rowHeight);
  background-color: pink;
  border-bottom: 1px solid red;
}
</style>

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值