微信小程序虚拟列表的应用实例

目录

  • 前言
  • 什么是虚拟列表?
  • demo效果
  • 准备工作
  • 屏高&盒子高度
  • 优化
  • 总结

前言 股票热门榜单有4000多条,渲染到页面上在盘中时还得实时更新,如果采用接口和分页,当下拉几十页的时候页面会变的越来越卡并且还得实时更新,最后的做法是一开始数据就从ws传递过来,我们只需要传起始下标和结束下标即可,在页面上我们也只生成几个标签。大大减轻了渲染压力。

什么是虚拟列表? 微信小程序虚拟列表的应用实例
文章图片

就只指渲染可视区域内的标签,在滚动的时候不断切换起始和结束的下标来更新视图,同时计算偏移。

demo效果 微信小程序虚拟列表的应用实例
文章图片


准备工作
  • 计算一屏可展示多少个列表。
  • 盒子的高度。
  • 滚动中起始位置。
  • 滚动中结束位置。
  • 滚动偏移量。

屏高&盒子高度 在小程序中我们可以利用wx.createSelectorQuery来获取屏高以及盒子的高度。
getEleInfo( ele ) {return new Promise( ( resolve, reject ) => {const query = wx.createSelectorQuery().in(this); query.select( ele ).boundingClientRect(); query.selectViewport().scrollOffset(); query.exec( res => {resolve( res ); })})},this.getEleInfo('.stock').then( res => {if (!res[0]) retuen; // 屏高this.screenHeight = res[1].scrollHeight; // 盒子高度this.boxhigh = res[0].height; })

起始&结束&偏移
onPageScroll(e) {let { scrollTop } = e; this.start = Math.floor(scrollTop / this.boxhigh); this.end = this.start + this.visibleCount; this.offsetY = this.start * this.boxhigh; }

scrollTop可以理解为距离顶部滚过了多少个盒子 / 盒子的高度 = 起始下标
起始 + 页面可视区域能展示多少个盒子 = 结束
起始 * 盒子高度 = 偏移
computed: {visibleData() {return this.data.slice(this.start, Math.min(this.end, this.data.length))},}

当start以及end改变的时候我们会使用slice(this.start,this.end)进行数据变更,这样标签的内容就行及时进行替换。

优化 快速滚动时底部会出现空白区域是因为数据还没加载完成,我们可以做渲染三屏来保证滑动时数据加载的比较及时。
prevCount() {return Math.min(this.start, this.visibleCount); },nextCount() {return Math.min(this.visibleCount, this.data.length - this.end); },visibleData() {let start = this.start - this.prevCount,end = this.end + this.nextCount; return this.data.slice(start, Math.min(end, this.data.length))},

如果做了前屏预留偏移的计算就要修改下:this.offsetY = this.start * this.boxhigh - this.boxhigh * this.prevCount
滑动动时候start、end、offsetY一直在变更,频繁调用setData,很有可能导致小程序内存超出闪退,这里我们在滑动的时候做个节流,稀释setData执行频率。
mounted() {this.deliquate = this.throttle(this.changeDeliquate, 130)},methods: {throttle(fn, time) {var previous = 0; return function(scrollTop) {let now = Date.now(); if ( now - previous > time ) {fn(scrollTop)previous = now; }}},changeDeliquate(scrollTop) {this.start = Math.floor(scrollTop / this.boxhigh); this.end = this.start + this.visibleCount; this.offsetY = this.start * this.boxhigh; console.log('执行setData')}},onPageScroll(e) { let { scrollTop } = e; console.log('滚动================>>>>>>>')this.deliquate(scrollTop); }

微信小程序虚拟列表的应用实例
文章图片

从上图可以看出,每次滚动差不多都降低了setData至少两次的写入。
文中编写的demo在这里,有需要的可以进行参考。

总结 【微信小程序虚拟列表的应用实例】到此这篇关于微信小程序虚拟列表应用的文章就介绍到这了,更多相关小程序虚拟列表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读