+
88
-

uniapp向上滚动虚拟列表加载更多无缝丝滑滚动如何实现?

uniapp向上滚动虚拟列表加载更多无缝丝滑滚动如何实现?


网友回复

+
18
-

800_auto

通过scroll监听和虚拟列表技术实现,完整代码如下:

<template>
  <view class="virtual-list">
    <scroll-view 
      class="scroll-view"
      scroll-y
      :scroll-top="scrollTop"
      :style="{ height: height + 'px' }"
      @scroll="onScroll"
      :scroll-with-animation="false"
    >
      <view class="loading" v-if="isLoading">加载中...</view>
      
      <view class="list-content" :style="{ height: totalHeight + 'px' }">
        <view 
          v-for="item in visibleData"
          :key="item.id"
          class="list-item"
          :style="{ transform: `translateY(${item.top}px)`, position: 'absolute', width: '100%' }"
        >
          <view :class="['message', item.isSelf ? 'self' : 'other']">
            <view class="avatar">{{item.isSelf ? '我' : '对方'}}</view>
            <view class="content">{{item.content}}</view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      height: 0,
      itemHeight: 80,
      visibleCount: 0,
      bufferCount: 5,
      listData: [],
      visibleData: [],
      isLoading: false,
      scrollTop: 0,
      startIndex: 0,
      loadMoreThreshold: 500,
      lastLoadTime: 0,
      loadCooldown: 1000,
      totalHeight: 0,
      lastScrollTop: 0,
      scrollTimeout: null
    }
  },

  async mounted() {
    const sysInfo = uni.getSystemInfoSync()
    this.height = sysInfo.windowHeight
    this.visibleCount = Math.ceil(this.height / this.itemHeight) + this.bufferCount * 2
    
    await this.initData()
  },

  methods: {
    async initData() {
      const initList = Array(30).fill(0).map((_, index) => ({
        id: index,
        content: `Message ${index}`,
        isSelf: Math.random() > 0.5,
        top: index * this.itemHeight
      }))
      
      this.listData = initList
      this.totalHeight = this.listData.length * this.itemHeight
      this.updateVisibleData()
    },

    updateVisibleData() {
...

点击查看剩余70%

+
18
-

思路:可以监听scroll事件,同时使用boundingClientRect技术获取第一个消息的top值,然后获取新的数据后,插...

点击查看剩余70%

我知道答案,我要回答