當滾動條滾動到最底端實現加載。
利用onReachBottom監聽方法
①下拉監聽方法
onReachBottom: function(){//上拉加載監聽方法 this.getMoreNews(); if(timer!=null){clearTimeout(timer);} timer=setTimeout(function(){ _self.getMoreNews(); },5000); },
②請求更多方法
getMoreNews:function(){ //判斷是否已經加載全部 if(_self.loadingTxt=='已經加載全部'){return false;} _self.loadingTxt='加載中'; //顯示加載中動畫 uni.showNavigationBarLoading(); //請求數據 uni.request({ url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page='+page, success:function(res){ console.log(res); uni.hideNavigationBarLoading(); if(res.data==null){ _self.loadingTxt='已經加載全部'; return false; } var newsList=res.data.split('--hcSplitor--'); _self.newsList=_self.newsList.concat(newsList); //成功獲取數據后結束下拉刷新 uni.stopPullDownRefresh(); //成功獲取數據后隱藏加載動畫 uni.hideNavigationBarLoading(); page++; _self.loadingTxt='加載更多'; } }) }
全部代碼:
<template>
<view >
<!-- 輪播圖 -->
<swiper indicator-dots="true" autoplay="true" >
<swiper-item>
<image src="/static/logo.png"></image>
</swiper-item>
<swiper-item>2</swiper-item>
<swiper-item>3</swiper-item>
</swiper>
<!-- 顯示數據 -->
<view v-for="(item,index) in newsList" class="newlist">
{{item}}
</view>
<!-- 加載視圖 -->
<view class="loading">{{loadingTxt}}</view>
</view>
</template>
<script>
var _self,page=1,timer=null;
export default {
data() {
return{
loadingTxt: '加載更多',
newsList: []
}
},
onLoad:function(){//初始化加載
this.getNews();
_self=this;
},
onPullDownRefresh:function(){//下拉刷新監聽方法
this.getNews();
},
onReachBottom: function(){//上拉加載監聽方法
this.getMoreNews();
if(timer!=null){clearTimeout(timer);}
timer=setTimeout(function(){
_self.getMoreNews();
},5000);
},
methods:{
getNews:function(){
page=1;
//顯示加載中動畫
uni.showNavigationBarLoading();
//請求數據
uni.request({
url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page='+page,
success:function(res){
console.log(res);
var newsList=res.data.split('--hcSplitor--');
_self.newsList=newsList;
//成功獲取數據后結束下拉刷新
uni.stopPullDownRefresh();
//成功獲取數據后隱藏加載動畫
uni.hideNavigationBarLoading();
page++;
}
})
},
getMoreNews:function(){
//判斷是否已經加載全部
if(_self.loadingTxt=='已經加載全部'){return false;}
_self.loadingTxt='加載中';
//顯示加載中動畫
uni.showNavigationBarLoading();
//請求數據
uni.request({
url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page='+page,
success:function(res){
console.log(res);
uni.hideNavigationBarLoading();
if(res.data==null){
_self.loadingTxt='已經加載全部';
return false;
}
var newsList=res.data.split('--hcSplitor--');
_self.newsList=_self.newsList.concat(newsList);
//成功獲取數據后結束下拉刷新
uni.stopPullDownRefresh();
//成功獲取數據后隱藏加載動畫
uni.hideNavigationBarLoading();
page++;
_self.loadingTxt='加載更多';
}
})
}
}
}
</script>
<style>
swiper-item{
background: #00FF00;
height: 200px;
width: 100%;
}
.newlist{
line-height: 2em;
padding:20px;
}
.loading{
line-height: 2em;
text-align: center;
color:#888;
margin-top: 30px;
}
</style>
以上代碼解決了:下拉刷新和上拉加載,並動態追加數據和延遲加載等細節。



