+
101
-

回答

原理就是正常向下加载更多加上flex的column-reverse;倒过来变成向上拉无感丝滑加载更多历史消息,适合聊天类历史消息查询,微信等就是采用这种方式,效果如下:

672984d6d3a52.gif

我们以uniapp实现,可以转换成微信小程序的代码的,代码如下:

点击查看完整代码

<template>
  <scroll-view :scroll-top="scrollTop" class="chat-container " scroll-y="true"   @scroll="onScroll" ref="chatContainer">
	  
    <view class="message-list" >
      <view v-for="(message, index) in messages" :key="index" class="message-item">
        <text>{{ message }}</text>
      </view>
	  <view class="space" :style="'height:'+spaceheight+'px;'"></view>
    </view>
  </scroll-view>
</template>
<script>
export default {
  data() {
    return {
		spaceheight:1000,//预留高度,用与无缝向上滚动
		pagesize:20,//,每一页大小
		scrollTop:0,
      messages: [], // 当前的消息列表
      page: 1, // 当前加载的页数
      isLoading: false, // 是否正在加载
    };
  },
  onLoad() {
    // 初次加载
    this.initData();
  },
  methods: {
	  
	  async initData(){
		   var that=this;
		  let newMessages=[];
		  for(let i =1; i <= that.pagesize; i ++) {
		       newMessages.push( `消息 第${this.page }页,第${i }条`);
		  }
		
		  
		  // 将新的消息添加到现有消息的开头
		  this.messages = newMessages;
		 this.page=this.page+1;
		  this.$nextTick(function(){
			  that.scrollTop=1200;
			  
		  })
		 
		  
	  },
    // 加载更多历史消息
    async loadMoreMessages() {
      if (this.isLoading) return;
      this.isLoading = true;
	   var that=this;

      // 模拟异步请求,实际应用中替换成API调用
      setTimeout(() => {
		  if(that.page>=10){
			  that.spaceheight=0;
			  uni.showToast({
			  	title:"没有更多了",
				icon:"none"
			  })
			  return;
		  }
        let newMessages=[];
         for(let i =1; i <= that.pagesize; i ++) {
              newMessages.push( `消息 第${that.page}页,第${i}条`);
         }
        		
         
       
       

        // 将新的消息添加到现有消息的开头
        that.messages = [ ...that.messages,...newMessages];
        that.page += 1;
        that.isLoading = false;
      }, 400);
    },
    // 滚动事件监听
    onScroll(event) {
      const { scrollTop } = event.detail;
	  console.log(scrollTop)
      if (scrollTop <1200 && !this.isLoading) {
        // 触发上拉加载
        this.loadMoreMessages();
      }
    },
  },
};
</script>



<style>
.chat-container {
 background-color: ghostwhite;
  height: 60vh; /* 让容器撑满屏幕高度 */
  overflow-y: auto; /* 开启滚动 */
}

.message-list {
  display: flex;
  flex-direction: column-reverse;
}

.message-item {
  padding: 10px;
  background-color: #f0f0f0;
  margin-bottom: 10px;
  border-radius: 5px;
}
</style>

网友回复

我知道答案,我要回答