0


虚拟列表(附带动态加载)原理及实现

前言

在前端的业务中,存在以下几种情况需要用到虚拟列表,旨在解决数据量庞大时浏览器渲染性能瓶颈。比如:

  • 1、导出报表数据不分页,数据量庞大
  • 2、移动端使用下拉加载分页列表,一直加载下一页时,数据量越来越大,无数的真实dom生成,对浏览器的渲染造成过大压力
  • 3、前端业务中许多树形数据处理,一般全部给到前端,如果一次性渲染出来,便会造成浏览器卡顿,如果把树数据结构看做一维的list来处理,结合虚拟列表就能解决性能瓶颈

以上便是我在工作中常见的场景,还有很多情况,就不一一列举了。

原理

虚拟列表也是可视化加载的一种,即只渲染可视容器中的内容。

假设有1万条记录需要同时渲染,我们屏幕的

  1. 可见区域

的高度为

  1. 500px

,而列表项的高度为

  1. 50px

,则此时我们在屏幕中最多只能看到10个列表项,那么在首次渲染的时候,我们只需加载10条即可。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-psMg5uP4-1658805024111)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1a51304d6b6c42e785c5e3ae3f21d99b~tplv-k3u1fbpfcp-watermark.image?)]

实现

虚拟列表的实现,实际上就是在首屏加载的时候,只加载

  1. 可视区域

内需要的列表项,当滚动发生时,动态通过计算获得

  1. 可视区域

内的列表项,并将

  1. 非可视区域

内存在的列表项删除。

  • 计算当前可视区域起始数据索引(startIndex)
  • 计算当前可视区域结束数据索引(endIndex)
  • 计算当前可视区域的数据,并渲染到页面中
  • 计算startIndex对应的数据在整个列表中的偏移位置startOffset并设置到列表上

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nUhn7xMB-1658805024112)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5fca76f0393d468bbd530dbbecdf6b9f~tplv-k3u1fbpfcp-watermark.image?)]

  1. <divclass="virtual-list-container"><divclass="virtual-list-place"></div><divclass="virtual-list"><!-- item-1 --><!-- item-2 --><!-- ...... --><!-- item-n --></div></div>
  • virtual-list-container可视区域的容器
  • virtual-list-place 为容器内的占位,高度为总列表高度,用于形成滚动条
  • virtual-list 为列表项的渲染区域

接着,监听

  1. virtual-list-container

  1. scroll

事件,获取滚动位置

  1. scrollTop
  • 假定可视区域高度固定,称之为screenHeight
  • 假定列表每项高度固定,称之为itemSize
  • 假定列表数据称之为listData
  • 假定当前滚动位置称之为scrollTop

则可推算出:

  • 列表总高度listHeight = listData.length * itemSize
  • 可显示的列表项数visibleCount = Math.ceil(screenHeight / itemSize)
  • 数据的起始索引startIndex = Math.floor(scrollTop / itemSize)
  • 数据的结束索引endIndex = startIndex + visibleCount
  • 列表显示数据为visibleData = listData.slice(startIndex,endIndex)

当滚动后,由于

  1. 渲染区域

相对于

  1. 可视区域

已经发生了偏移,此时我需要获取一个偏移量

  1. startOffset

,通过样式控制将

  1. 渲染区域

偏移至

  1. 可视区域

中。

  • 偏移量startOffset = scrollTop - (scrollTop % itemSize);

列表项高度不固定

在之前的实现中,列表项的高度是固定的,因为高度固定,所以可以很轻易的获取列表项的整体高度以及滚动时的显示数据与对应的偏移量。而实际应用的时候,当列表中包含文本之类的可变内容,会导致列表项的高度并不相同。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rZH5QFIz-1658805024112)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e96e61b783d046e8a5d758088e275be1~tplv-k3u1fbpfcp-watermark.image?)]

在虚拟列表中应用动态高度的解决方案一般有如下三种:

1.对组件属性

  1. itemSize

进行扩展,支持传递类型为

  1. 数字

  1. 数组

  1. 函数
  • 可以是一个固定值,如 100,此时列表项是固高的
  • 可以是一个包含所有列表项高度的数据,如 [50, 20, 100, 80, …]
  • 可以是一个根据列表项索引返回其高度的函数:(index: number): number

这种方式虽然有比较好的灵活度,但仅适用于可以预先知道或可以通过计算得知列表项高度的情况,依然无法解决列表项高度由内容撑开的情况。

2.将列表项

  1. 渲染到屏幕外

,对其高度进行测量并缓存,然后再将其渲染至可视区域内。

由于预先渲染至屏幕外,再渲染至屏幕内,这导致渲染成本增加一倍,这对于数百万用户在低端移动设备上使用的产品来说是不切实际的。

3.以

  1. 预估高度

先行渲染,然后获取真实高度并缓存。

这是我选择的实现方式,可以避免前两种方案的不足。

接下来,来看如何简易的实现:

定义组件属性

  1. itemHeight

,用于接收

  1. 预估高度
  1. props:{//预估高度 itemHeight:{type:Number
  2. }}

定义

  1. positions

,用于列表项渲染后存储

  1. 每一项的高度以及位置

信息,

  1. this.positions = [
  2. // {
  3. // top:0,
  4. // bottom:100,
  5. // height:100
  6. // }
  7. ];

由于需要在

  1. 渲染完成

后,获取列表每项的位置信息并缓存,所以使用钩子函数

  1. updated

来实现:

  1. updated(){let nodes =this.$refs.items;
  2. nodes.forEach((node)=>{let rect = node.getBoundingClientRect();let height = rect.height;let index =+node.id.slice(1)let oldHeight =this.positions[index].height;let dValue = oldHeight - height;//存在差值if(dValue){this.positions[index].bottom =this.positions[index].bottom - dValue;this.positions[index].height = height;for(let k = index +1;k<this.positions.length; k++){this.positions[k].top =this.positions[k-1].bottom;this.positions[k].bottom =this.positions[k].bottom - dValue;}}})}

vue版本的代码实现

组件VirtualList:

  1. <template>
  2. <div ref="listContainerRef" class="virtual-list-container" :style="{height}" @scroll="onScroll">
  3. <div ref="listPlaceRef" class="virtual-list-place"></div>
  4. <div ref="listRef" class="virtual-list">
  5. <div
  6. ref="itemsRef"
  7. class="virtual-list-item"
  8. v-for="(item, itemIndex) in visibleList"
  9. :key="item._key"
  10. :id="item._key"
  11. >
  12. <slot name="default" :item="item" :index="itemIndex"></slot>
  13. </div>
  14. </div>
  15. <slot name="footer"></slot>
  16. </div>
  17. </template>
  18. <script>
  19. export default {
  20. props: {
  21. // 首尾缓存比例 = (首或者尾高度 + 滚动视窗高度) / 滚动视窗高度
  22. // 自动高度开启时需要调大缓存区比例(视窗内能容纳的越多该值应该越大)
  23. bufferScale: {
  24. type: Number,
  25. default: 0.4,
  26. requred: false
  27. },
  28. // 数据
  29. dataSource: {
  30. type: Array,
  31. requred: true
  32. },
  33. // 滚动视窗高度
  34. height: {
  35. type: String,
  36. default: '100%',
  37. requred: false
  38. },
  39. // (非必填)列表每一项高度(不填时需开启itemAutoHeight)
  40. itemHeight: {
  41. type: Number,
  42. default: 60,
  43. requred: false
  44. },
  45. // 是否自动计算每一项高度
  46. itemAutoHeight: {
  47. type: Boolean,
  48. default: false
  49. },
  50. // 到达底部回调
  51. onReachBottom: Function
  52. },
  53. data () {
  54. return {
  55. screenHeight: 0,
  56. startIndex: 0,
  57. endIndex: 0,
  58. positions: []
  59. }
  60. },
  61. computed: {
  62. _listData () {
  63. return this.dataSource.map((item, index) => ({
  64. ...item,
  65. _key: `${index}`
  66. }))
  67. },
  68. anchorPoint () {
  69. return this.positions.length ? this.positions[this.startIndex] : null
  70. },
  71. visibleCount () {
  72. return Math.ceil(this.screenHeight / this.itemHeight)
  73. },
  74. aboveCount () {
  75. return Math.min(this.startIndex, Math.ceil(this.bufferScale * this.visibleCount))
  76. },
  77. belowCount () {
  78. return Math.min(this._listData.length - this.endIndex, Math.ceil(this.bufferScale * this.visibleCount))
  79. },
  80. visibleList () {
  81. const startIndex = this.startIndex - this.aboveCount
  82. const endIndex = this.endIndex + this.belowCount
  83. return this._listData.slice(startIndex, endIndex)
  84. }
  85. },
  86. mounted () {
  87. this.init()
  88. },
  89. updated () {
  90. // 列表数据长度不等于缓存长度
  91. if (this._listData.length !== this.positions.length) {
  92. this.initPositions()
  93. }
  94. this.$nextTick(function () {
  95. if (!this.$refs.itemsRef || !this.$refs.itemsRef.length) {
  96. return
  97. }
  98. // 获取真实元素大小,修改对应的尺寸缓存
  99. if (this.itemAutoHeight) {
  100. this.updateItemsSize()
  101. }
  102. // 更新列表总高度
  103. const height = this.positions[this.positions.length - 1].bottom
  104. this.$refs.listPlaceRef.style.height = height + 'px'
  105. // 更新真实偏移量
  106. this.setStartOffset()
  107. })
  108. },
  109. methods: {
  110. init () {
  111. this.initPositions()
  112. this.screenHeight = this.$refs.listContainerRef.clientHeight
  113. this.startIndex = 0
  114. this.endIndex = this.visibleCount
  115. this.setStartOffset()
  116. },
  117. initPositions () {
  118. this.positions = this._listData.map((_, index) => ({
  119. index,
  120. height: this.itemHeight,
  121. top: index * this.itemHeight,
  122. bottom: (index + 1) * this.itemHeight
  123. })
  124. )
  125. },
  126. updateItemsSize () {
  127. const nodes = this.$refs.itemsRef
  128. nodes.forEach((node) => {
  129. const rect = node.getBoundingClientRect()
  130. const height = rect.height
  131. const index = +node.id.split('_')[0]
  132. const oldHeight = this.positions[index].height
  133. const dValue = oldHeight - height
  134. if (dValue) {
  135. this.positions[index].bottom = this.positions[index].bottom - dValue
  136. this.positions[index].height = height
  137. this.positions[index].over = true
  138. for (let k = index + 1; k < this.positions.length; k++) {
  139. this.positions[k].top = this.positions[k - 1].bottom
  140. this.positions[k].bottom = this.positions[k].bottom - dValue
  141. }
  142. }
  143. })
  144. },
  145. setStartOffset () {
  146. let startOffset
  147. if (this.startIndex >= 1) {
  148. const size = this.positions[this.startIndex].top - (this.positions[this.startIndex - this.aboveCount] ? this.positions[this.startIndex - this.aboveCount].top : 0)
  149. startOffset = this.positions[this.startIndex - 1].bottom - size
  150. } else {
  151. startOffset = 0
  152. }
  153. this.startOffset = startOffset
  154. this.$refs.listRef.style.transform = `translate3d(0,${startOffset}px,0)`
  155. },
  156. getStartIndex (scrollTop = 0) {
  157. return this.binarySearch(this.positions, scrollTop)
  158. },
  159. binarySearch (list, value) {
  160. let start = 0
  161. let end = list.length - 1
  162. let tempIndex = null
  163. while (start <= end) {
  164. const midIndex = parseInt((start + end) / 2)
  165. const midValue = list[midIndex].bottom
  166. if (midValue === value) {
  167. return midIndex + 1
  168. } else if (midValue < value) {
  169. start = midIndex + 1
  170. } else if (midValue > value) {
  171. if (tempIndex === null || tempIndex > midIndex) {
  172. tempIndex = midIndex
  173. }
  174. end = end - 1
  175. }
  176. }
  177. return tempIndex
  178. },
  179. onScroll () {
  180. const scrollTop = this.$refs.listContainerRef.scrollTop
  181. const scrollHeight = this.$refs.listContainerRef.scrollHeight
  182. if (scrollTop > this.anchorPoint.bottom || scrollTop < this.anchorPoint.top) {
  183. this.startIndex = this.getStartIndex(scrollTop)
  184. this.endIndex = this.startIndex + this.visibleCount
  185. this.setStartOffset()
  186. }
  187. if (scrollTop + this.screenHeight > scrollHeight - 50) {
  188. this.onReachBottom && this.onReachBottom()
  189. }
  190. }
  191. }
  192. }
  193. </script>
  194. <style>
  195. .virtual-list-container {
  196. overflow: auto;
  197. position: relative;
  198. }
  199. .virtual-list-place {
  200. position: absolute;
  201. left: 0;
  202. top: 0;
  203. right: 0;
  204. z-index: -1;
  205. }
  206. .virtual-list {
  207. position: absolute;
  208. left: 0;
  209. top: 0;
  210. right: 0;
  211. z-index: 1;
  212. }
  213. </style>

固定列表项高度使用组件

  1. <template>
  2. <VirtualList :dataSource="list" :itemHeight="22">
  3. <template v-slot="{item}">
  4. <div>{{item.value}}</div>
  5. </template>
  6. </VirtualList>
  7. </template>
  8. <script>
  9. import VirtualList from '@/components/VirtualList'
  10. export default {
  11. components: { VirtualList },
  12. data () {
  13. return {
  14. list: new Array(100).fill(0).map((_, index) => ({ value: index + 1 }))
  15. }
  16. }
  17. }
  18. </script>

动态列表项高度使用组件

开启

  1. itemAutoHeight

,并且设置

  1. bufferScale

比例来增加上下缓冲区大小保证加载的内容能撑满可视区域

  1. <template>
  2. <VirtualList :dataSource="list" :itemHeight="22" :itemAutoHeight="true" :bufferScale="1.2">
  3. <template v-slot="{item}">
  4. <div>{{item.value}}</div>
  5. </template>
  6. </VirtualList>
  7. </template>
  8. <script>
  9. import VirtualList from '@/components/VirtualList'
  10. export default {
  11. components: { VirtualList },
  12. data () {
  13. return {
  14. list: new Array(100).fill(0).map((_, index) => ({ value: index + 1 }))
  15. }
  16. }
  17. }
  18. </script>

与分页结合时使用

在onReachBottom中做接口请求,这样的话既能通过分页优化,又能在加载的数据量大的时候采用虚拟列表方案

  1. <template>
  2. <VirtualList
  3. :dataSource="list"
  4. :itemHeight="22"
  5. :itemAutoHeight="true"
  6. :bufferScale="1.2"
  7. :onReachBottom="fetchList"
  8. >
  9. <template v-slot="{item}">
  10. <div>{{item.value}}</div>
  11. </template>
  12. </VirtualList>
  13. </template>
  14. <script>
  15. import VirtualList from '@/components/VirtualList'
  16. let page = 1
  17. export default {
  18. components: { VirtualList },
  19. data () {
  20. return {
  21. list: new Array(100).fill(0).map((_, index) => ({ value: `${page}_${index + 1}` }))
  22. }
  23. },
  24. methods: {
  25. fetchList () {
  26. page += 1
  27. const list = new Array(100).fill(0).map((_, index) => ({ value: `${page}_${index + 1}` }))
  28. this.list = [...this.list, ...list]
  29. }
  30. }
  31. }
  32. </script>

稳定npm推荐

  • react相关npm包
  1. // 虚拟列表
  2. npm i -S react-window
  3. // 虚拟表格
  4. npm i -S virtuallist-antd
  • react相关npm包
  1. // 虚拟列表
  2. npm i -S vue-virtual-scroll-list
  3. // 虚拟表格
  4. npm i -S vxe-table
标签: 前端 javascript html

本文转载自: https://blog.csdn.net/qq_42036203/article/details/125990867
版权归原作者 qq_42036203 所有, 如有侵权,请联系我们删除。

“虚拟列表(附带动态加载)原理及实现”的评论:

还没有评论