0
点赞
收藏
分享

微信扫一扫

uniapp实现下拉请求新的一页(可添加查询)

源码之路 2022-03-12 阅读 89
<template>
	<view>
        <view class="container">
			<view class='taskShow' v-for="(item,index) in taskList" :key="index">
                <view>{{item.请求到的key}}</view><!-- 改成自己的 -->
			</view>		
	    </view>
        <!-- 显示加载中或者全部加载完成 -->
        <view v-show="isLoadMore"> 
		      <uni-load-more :status="loadStatus"></uni-load-more>
	    </view>	
    </view>
</template>

<script>
	export default {
		data() {
			return {
				taskList:[],//存储请求到的内容
                page:1,
                pagesize:10,
                loadStatus:'loading',  //加载样式:more-加载前样式,loading-加载中样式,nomore-没有数据样式
                isLoadMore:false,  //是否加载中
			};
		},
		onShow(options) {
			this.getTaskList()
		},
		onReachBottom(){  //上拉触底函数
			if(!this.isLoadMore){  //此处判断,上锁,防止重复请求
				this.isLoadMore=true
                this.page+=1  //每次上拉请求新的一页
                this.getTaskList()    
			}
		},
		methods:{
			getTaskList(){
				const app = this
                uni.request({
			    	url:'/api/index',//你的接口或者json文件
			        method: 'GET',
					data:{
						page:app.page,
                        pagesize:10,
					},
			        success: res => {
			            if(true){
			                    if(res.data.data.data){
			                        this.taskList=this.taskList.concat(res.data.data.data)
			                        if(res.data.data.data.length<this.pagesize){  //判断接口返回数据量小于请求数据量,则表示此为最后一页
			                            this.isLoadMore=true                                             
			                            this.loadStatus='nomore'
			                        }else{
			                            this.isLoadMore=false
			                        }
			                    }else{
			                        this.isLoadMore=true
			                        this.loadStatus='nomore'
			                    }
			            }else{  //接口请求失败的处理
			                uni.showToast({title:res.data.msg,icon:'none'})
			                this.isLoadMore=false
			                if(this.page>1){
			                    this.page-=1 
			                }
			            }
			        },
			        fail: () => {  //接口请求失败的处理
			            uni.showToast({title: '服务器开小差了呢,请您稍后再试',icon:'none'})
			        },
			    });
			},
		}
	}
</script>

<style>
.taskShow{
	border-radius: 20rpx;
	margin: 0 auto;
	width: 690rpx;
	height: 235rpx;
	background-color: #FFFFFF;
	margin-top: 20rpx;
	overflow: hidden;
	display: flex;
}
</style>

以上是完整代码,正常的请求,只是增加了上拉函数(请求下一页函数)。要注意的是:

1、避免在用户上拉请求时如果用户再次上拉出现又请求了一页的Bug,可以通过用函数包裹来实现异步,也可以通过vuex实现异步请求。

2、如果请求请求下一页失败,页码要不变。例如你在第一页请求第二页失败了,下次请求第二页却因为page已经等于3而请求到了第三页。

如果分页是带搜索的或者分类的,只需要修改后端代码传入模糊搜索参数,前端在data中再传入搜索的内容就可以了。

举报

相关推荐

0 条评论