实现上拉刷新下拉加载

299 阅读1分钟

1.首页我们一定要在 page.json 页面中配置enablePullDownRefresh"样式,当它的值为true的时候,页面就能支持上拉刷新和下拉加载两个方法配置onReachBottomDistance ,值是距离底部多少的时候会触发``onReachBottom。这个函数

   {
   "path" : "pages/popularization/popularization",
            "style" :                                                                                    
            {
                "navigationBarTitleText": "科普专区",
                "enablePullDownRefresh": true,
                "onReachBottomDistance": 100
            }
            
        }

2.需要可以在页面中,onLoad 开启或者mounted 中开启,上拉刷新这个动作

3.使用onPullDownRefresh 页面周期函数,写一个定时器将这个上拉刷新动作给关掉

4.在做上拉刷新这个动作时,将最新的数据设置为初始页

onLoad(){
this.index() //这里进入可以直接调用接口
//uni.startPullDownRefresh() //开启下拉刷新,可以在一开始进入页面不刷新
},
//页面一进来就会执行下面这个函数,进行刷新动作,然后关闭
onPullDownRefresh() {this.index() //这里调需要调一下接口
//这段话在在微信小程序可以自动结束,但是在H5 中不行需要手动结束
setTimeout(function(){
uni.stopPullDownRefresh() //关闭上拉刷新这个动作
},1000)
},

二、实现下拉加载

4.在data里面定义 currentPage:1 默认第一页

data(){
return{
currentPage:1, //展示第几页数据,默认第一页
arrmessage:[] //数据
}
}

5.在页面配置,页面下拉函数,每次下拉页面递增,请求接口,新的数据

//下拉出发的函数
onReachBottom() {
this.currentPage++ //1.下拉完之后
index() //2.调用接口			
}

6.请求接口配置,如果page==1 进入页面直接显示首页数据,否则将最新的数据和原来的数据拼接,成为新的数组

async index(){
// 进入资讯接口
let res=await this.$myRequest({
url:'intomessagearea',
data:{
   page:this.current_page 
})
if(this.current_page==1){
this.arrmessage=res.data.arrmessage.data
}
// 处理数据:这里主要是对之前数据做一个拼接
this.arrmessage=[...this.arrmessage,...res.data.arrmessage.data]
this.current_page=res.data.arrmessage.current_page
},