美文网首页
大量数据渲染滚动优化方案demo

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

作者: 小小小菠菜吖 | 来源:发表于2020-09-18 16:28 被阅读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>

相关文章

网友评论

      本文标题:大量数据渲染滚动优化方案demo

      本文链接:https://www.haomeiwen.com/subject/ldujyktx.html