蓝天白云蓝天白云
2023-05-02
vue
93

使用 Vue 实现一个简单的虚拟滚动

当我们需要展示大量数据时,使用滚动列表可以使得用户浏览数据变得更加简单方便。然而,由于大量的数据需要一次性渲染,这可能会导致性能问题,尤其是在移动设备上。为了解决这个问题,可以使用虚拟滚动的技术。

虚拟滚动是一种优化长列表性能的技术,它通过动态渲染可视区域内的列表项,避免一次性渲染所有项导致的性能问题。具体来说,虚拟滚动将可视区域内和周围的列表项渲染出来,并且在用户滚动列表时,动态地添加和删除项,从而保证渲染的元素数量尽可能少。

实现虚拟滚动的方式有多种,其中最简单的方式是基于浏览器自带的 scroll 事件和 DOM 元素操作实现,下面是一个 Vue 实现一个简单的虚拟滚动的代码示例:

设计思路

  1. 使用 padding 占用虚拟空间,避免频繁操作 DOM。

  2. 配置参数包括:单个元素高度 height、容器高度 mainHeight、预加载临界值数量 preLoadNum、数据源 listResource。

  3. 变量 top(代表顶部不加载的 DOM 元素个数)和 bottom(代表底部不加载的 DOM 元素个数)与 paddingTop 和 paddingBottom 相关联。

  4. 预加载数量需要考虑顶部和底部的,也就是说预加载的数量最多只能是 2*preLoadNum。

  5. scroll 事件和 DOM 元素操作实现,dom操作交个vue去实现了

实现代码

<template>
 <div class="main" :style="{ height: mainHeight + 'px' }" @scroll="divScroll($event)">
   <div :style="{ paddingTop, paddingBottom }" class="content" ref="content">
     <div :style="{ height: height + 'px' }" v-for="item in list" :key="item">{{item}}div>
   div>
 div>
​
template>
​
<script>1
export default {
 data() {
   return {
     scrollTop: 0,
     top: 0,
     bottom: 0,
  }
},
 props: {
   listResource: { //数据源
     default: () => [...new Array(100)].map((item, index) => index)
  },
   mainHeight: { // 容器高度
     default: 500
  },
   height: { // 元素高度
     default: 50
  },
   preLoadNum: { //预加载数量
     default: 10
  },
},
 computed: {
   paddingTop() {
     return this.top * this.height + 'px';
  },
   paddingBottom() {
     return this.bottom * this.height + 'px';
  },
   showNums() { // 可视区域最多可展示数量
     return Math.ceil(this.mainHeight / this.height);
  },
   list() {  // 需要渲染的列表
     return this.listResource.slice(this.top, this.listResource.length - this.bottom)
  },
​
},
 methods: {
   divScroll(event) {
     const scrollTop = Math.floor(event.target.scrollTop / this.height)
     if (scrollTop !== this.scrollTop) {
       this.scrollTop = scrollTop;
       this.top = this.getTop();
       this.bottom = this.getBottom();
       console.log(this.scrollTop, this.top, this.bottom)
    }
  },
   getTop() { // 临界条件就是顶部可预加载的数量不足 preLoadNum
     if (this.scrollTop > this.preLoadNum) {
       return this.scrollTop - this.preLoadNum;
    } else {
       return 0;
    }
  },
   getBottom() { // 临界条件就是底部可预加载的数量不足 preLoadNum
     if (this.listResource.length - this.scrollTop - this.showNums > this.preLoadNum) {
       return this.listResource.length - this.showNums - this.preLoadNum - this.scrollTop;
    } else {
       return 0;
    }
  }
},
 created() {
   this.bottom = this.getBottom();
}
}
script>
​
<style scoped>
 .main {
   overflow: auto;
}
​
 .content {
   width: 100%;
}
​
 .content > div:nth-child(2n) {
   background-color: #cccccc;
}
style>
​

上面代码只是实现了一些皮毛,还有极大的优化空间。

虚拟滚动是一种非常实用的技术,可以显著提高大量数据的呈现性能。当在实际项目中使用时,还需要考虑更多的细节和性能问题,例如如何优化 DOM 操作、如何处理异步数据等。

Tags

Vue Router(四)优化
上一篇
Vue Router(四)优化
下一篇
没有啦