uniapp小程序页面上拉加载更多功能实现

4,640 阅读1分钟

微信小程序页面,一般都会有上拉加载更多功能,这个和传统的vue表格分页还是有点区别的,前者是从接口返回结果,拿到当前页面的大小,当前页等参数,后者是通过点击获取当前索引当参数,具体实现,如下:

  • 页面结构:
 <scroll-view scroll-y="true" show-scrollbar='false' class="main" :style="{height:scrollHeight}" @scrolltolower="scrolltolower">
    <view class="record" v-for="(item,index) in recordList" :key='index'>
	<view class="recordRight">
	    <view class="statusIcon" :class="`statusIcon`+item.type"></view>
		<view class="recordInfo">
		    <view class="statusAndTime">
			<view class="status" v-cloak>{{item.title}}</view>
			<view class="time">{{item.date}}</view>
		    </view>
		    <view class="money" :class="[item.count > 0 ? 'status1' : 'statusStyle' ]" v-cloak>{{item.count > 0 ? '+' + item.count : item.count}}</view></view>
	    </view>
	</view>
	<view class="noMoreData" v-if="noMoreData">没有更多记录了</view>
</scroll-view>
注意:scroll-y="true"表示可以垂直滑动
      :style="{height:scrollHeight}"为一进入页面获取页面高度
       @scrolltolower="scrolltolower"当滑到底部触发的函数
  • 逻辑页面:
 <script>
    export default {
	data() {
	    return {
		recordList:[],
		scrollHeight:'0', // 初始化页面时获取页面高度
		maxIndex: 0,
		minIndex: 0,
		noMoreData:false
	    }
	},
	created() {
	    this.getRecord()
	    this.initScrollHeight()
	},
	methods:{
	    getRecord() {
		this.$api.post('', {
		    userid: this.userId,
		    max_index: this.maxIndex,  // 当前页面显示的条数
		    min_index: this.minIndex // 第几页
		}).then((res) => {
		    if(res.data.RequestStatus === 100) {
		        this.maxIndex=res.data.Data.max_index // 将接口的显示条数存起来,当下拉到底部的时候回传
			this.minIndex=res.data.Data.min_index // 将接口每次滑到底部的页数存起来,用于回传显示当前页数下的数据
			this.recordList=this.recordList.concat(res.data.Data.record_list) // 将每页的数据汇总起来
			if(this.minIndex<=1) {this.noMoreData=true} // 当前页为<=1时,显示无数据
		    } else {
			this.$showToast(res.data.Msg)
		    }
			if(this.recordList.length<=0){this.noMoreData=true}
		})
	},
	
	// 初始化页面时获取页面高度
	initScrollHeight(){
	    let _self=this // success的作用域是闭合作用域,所以要重新声明一个this
	    uni.getSystemInfo({
		success: function (res) {
		    _self.scrollHeight=res.windowHeight+'px'
		}
	    })
	},
	
	// 当每次滑动到底部再次请求接口,实现上啦加载更多刷新
	scrolltolower(){
	    if(!this.noMoreData){
		this.getRecord()
	    }
        }