How does the uniapp applet use the virtual list to cooperate with throttling to complete the pull-up refresh and pull-down loading, avoid page freezes, and improve performance?

This article will introduce how to use the virtual list and throttling technologies in the uniapp applet to realize the pull-up refresh and pull-down loading function, and at the same time avoid the page freeze problem caused by rendering a large amount of data.

1. Virtual list

In the development of uniapp applets, when we need to render a large amount of list data, it is easy to get stuck on the page. At this time, we can use virtual list technology to optimize performance.

The so-called virtual list is to divide all data into two parts: visible area and non-visible area. Only the data in the visible area will be rendered, and the data not in the visible area will not be rendered temporarily, which can greatly reduce the number of DOM operations and improve rendering efficiency.

In the uniapp applet, using the uni-scroll-view component in uni-app needs to be installed in the plug-in market

<template>
  <uni-scroll-view :style="{height: height + 'px'}" @scroll="onScroll">
    <ul>
      <li v-for="(item, index) in visibleData" :key="index">{
   
   { item }}</li>
    </ul>
  </uni-scroll-view>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      // 总数据
      data: [],
      // 可视区域高度
      height: 0,
      // 可视区域顶部数据序号
      startIndex: 0,
      // 可视区域底部数据序号
      endIndex: 0,
      // 可视区域数据
      visibleData: []
    };
  },
  mounted() {
      
      
    // 初始化数据
    this.initData();
    // 监听可视区域高度变化
    uni.getSystemInfo({
      
      
      success: (res) => {
      
      
        this.height = res.windowHeight;
      }
    });
  },
  methods: {
      
      
    initData() {
      
      
      // 生成大量数据
      for (let i = 0; i < 10000; i++) {
      
      
        this.data.push(`数据 ${ 
        i+1}`);
      }
      // 初始化可视区域数据
      this.visibleData = this.data.slice(0, 30);
      this.endIndex = 29;
    },
    onScroll(e) {
      
      
      // 滚动事件
      const scrollTop = e.detail.scrollTop;
      const itemHeight = 50; // 每个数据项高度
      const visibleCount = Math.ceil(this.height / itemHeight); // 可见数据项个数
      const startIndex = Math.floor(scrollTop / itemHeight); // 开始渲染的数据序号

      if (startIndex !== this.startIndex) {
      
      
        this.startIndex = startIndex;
        this.endIndex = this.startIndex + visibleCount - 1;
        this.visibleData = this.data.slice(this.startIndex, this.endIndex + 1);
      }
    }
  }
}
</script>

In this sample code, we use the uni-scroll-view component to wrap the list content, and initialize the total data and the height of the visible area in the mounted hook function, and listen to the scroll event.
When the user scrolls the list, we calculate the range of data that should be displayed in the current visible area according to the scroll distance and the height of each data item, update the visibleData array, and render it. In this way, only the data in the visible area will be rendered, and the data not in the visible area will not be rendered, thereby greatly reducing the number of DOM operations and improving rendering efficiency.

Two, throttling

In addition to using virtual lists to optimize rendering efficiency, we can also use throttling technology to control the execution frequency of functions, so as to avoid page freeze problems caused by frequent operations.

In the uniapp applet, we can use the throttle method in the Lodash library to achieve throttling. First, install the Lodash library in the pages that need to use throttling:

npm install lodash

Then, introduce the throttle method in the Lodash library in the vue file, and use this method to wrap the function that needs to be throttled:

<template>
  <view>
    <uni-virtual-list :list="list" :item-size="50" :keep-alive="10" class="list">
      <view slot="default" class="item">{
   
   { item.text }}</view>
    </uni-virtual-list>
  </view>
</template>
<script>
import _ from 'lodash'

export default {
      
      
  data() {
      
      
    return {
      
      
      list: [
        {
      
       id: 1, text: 'item 1' },
        {
      
       id: 2, text: 'item 2' },
        ...
      ]
    }
  },
  created() {
      
      
    this.throttledScrollHandle = _.throttle(this.scrollHandle, 300)
  },
  methods: {
      
      
    scrollHandle() {
      
      
      // 处理滚动事件
    }
  },
  mounted() {
      
      
    uni.pageScrollTo({
      
       scrollTop: 0 })
    uni.pageScrollTo({
      
       scrollTop: 1000 })
    uni.$on('pageScroll', this.throttledScrollHandle)
  },
  destroyed() {
      
      
    uni.$off('pageScroll', this.throttledScrollHandle)
  }
}
</script>

Through the above code, we use the throttle method in the Lodash library to wrap the scrollHandle function, thus realizing the throttling of the function. When the page is mounted, we also need to bind the scrollHandle function to the page scrolling event, and set an interval to control the execution frequency of the function.

3. Pull up to refresh and pull down to load

On the basis of virtual list and throttling, we can implement pull-up refresh and pull-down loading functions. At this time, we need to monitor the scrolling event of the page, and trigger the corresponding operation when scrolling to the bottom or top of the page.

The specific implementation is as follows:

<template>
  <view>
    <uni-virtual-list :list="list" :item-size="50" :keep-alive="10" class="list">
      <view slot="default" class="item">{
   
   { item.text }}</view>
    </uni-virtual-list>
  </view>
</template>
<script>
import _ from 'lodash'

export default {
      
      
  data() {
      
      
    return {
      
      
      list: [
        {
      
       id: 1, text: 'item 1' },
        {
      
       id: 2, text: 'item 2' },
        ...
      ]
    }
  },
  created() {
      
      
    this.throttledScrollHandle = _.throttle(this.scrollHandle, 300)
  },
  methods: {
      
      
    scrollHandle(e) {
      
      
      const {
      
       scrollTop, scrollHeight, windowHeight } = e.detail
      if (scrollTop < 10) {
      
      
        // 上拉刷新
      } else if (scrollTop + windowHeight > scrollHeight - 10) {
      
      
        // 下拉加载
      }
    }
  },
  mounted() {
      
      
    uni.pageScrollTo({
      
       scrollTop: 0 })
    uni.$on('pageScroll', this.throttledScrollHandle)
  },
  destroyed() {
      
      
    uni.$off('pageScroll', this.throttledScrollHandle)
  }
}
</script>

In the above code, we use the properties such as scrollTop, scrollHeight and windowHeight in the page scrolling event e.detail to calculate whether the current page has scrolled to the bottom or top, and trigger the corresponding operation, thus realizing the pull-up refresh and pull-down loading functions.

Summarize

To sum up, through the optimization of virtual list technology and throttling technology, we can realize the pull-up refresh and pull-down loading functions in the uniapp applet, and avoid the page jam problem caused by a large amount of data rendering, and improve the fluency and stability of the page.

Guess you like

Origin blog.csdn.net/weixin_63929524/article/details/130471091
Recommended