大量数据渲染滚动优化方案demo

2020-09-18  本文已影响0人  小小小菠菜吖

dom区域

<template>
  <div class="more-data-scroll">
    <header>大量数据渲染滚动优化demo</header>
    <section @scroll="handleScroll" ref="scrollBox">
      <ul ref="scroll">
        <li v-for="item in showArr" :key="item">{{ item }}</li>
      </ul>
    </section>
  </div>
</template>

JS区域

<script>
export default {
  data() {
    return {
      num: 100,//模拟的数据条目数
      showArr: []//展示的数组
    };
  },
  mounted() {
    //   初次挂载获取截取展示数组
    this.handleScroll();
  },
  methods: {
    handleScroll() {
      // 获取最外层盒子的高度
      const boxHeight = this.$refs.scrollBox.offsetHeight;
      //   计算每一页应该展示多少条目并在结尾追加多余的几个条目
      const showNum = Math.ceil(boxHeight / 35) + 5;
      //   根据滚出的高度计算当前截取的其实下标
      const startIndex = Math.floor(this.$refs.scrollBox.scrollTop / 35);
      if (startIndex + showNum - 5 < this.num.length) {
        //   获取展示的截取数组
        this.showArr = this.num.slice(startIndex, startIndex + showNum);
        // 当滚动出一定距离后利用marginTop来填充
        this.$refs.scroll.style.marginTop = this.$refs.scrollBox.scrollTop + 'px';
      }
    }
  }
};
</script>

样式区域

<style lang="scss" scoped>
.more-data-scroll section{
    width:600px;
    height:600px;
    background: burlywood;
    border:solid 1px #ccc;
    overflow: auto;
    li{
        height:35px;
        line-height: 35px;
        border-bottom: solid 1px #ccc;
    }
}
</style>

上一篇 下一篇

猜你喜欢

热点阅读