uni-app教程七(下拉刷新、上拉加载)

下拉刷新

定义 onPullDownRefresh 处理函数(和onLoad等生命周期函数同级),监听该页面用户下拉刷新事件。

  • 需要在 pages.json 里,找到的当前页面的pages节点,并在 style 选项中开启 enablePullDownRefresh。

在这里插入图片描述
在组件中使用下拉刷新:
在这里插入图片描述

上拉加载

onReachBottom
页面滚动到底部的事件(不是scroll-view滚到底),常用于上拉加载下一页数据。如使用scroll-view导致页面级没有滚动,则触底事件不会被触发

源码如下:

<template>
    <view class="box">
     <view v-for="(item, index) in newsList" class="newslist">
		  <view class="item">  
			  {
   
   {item.title}}  
		  </view>
     </view>
     <view class="loading">{
   
   {loadingText}}</view>
 </view>
</template>
<script>
var _self, page = 1, timer = null;
export default {
     
     
 data(){
     
     
	 return{
     
     
		 newsList:[],
		 loadingText:'加载中...'
	 }
 
 },
 //页面加载
 onLoad(){
     
     
  _self = this;
  //获取首页数据
   this.getnewsList()
    },
	
 // 下拉刷新,初始化第一页数据
 onPullDownRefresh(){
     
     
  this.getnewsList();
 },
 //页面滚动到底部的事件
 onReachBottom(){
     
     
  if(timer != null){
     
     
   clearTimeout(timer);
  }
  timer = setTimeout(function(){
     
     
	//加载更多数据
   _self.getmorenews();
  }, 1000);
 },
 methods:{
     
     
  getmorenews(){
     
     
   if(_self.loadingText != '' && _self.loadingText != '加载更多'){
     
     
    return false;
   }
   _self.loadingText = '加载中...';
   //在当前页面显示导航条加载动画。
   uni.showNavigationBarLoading();
   uni.request({
     
     
   url: 'https://ceshi2.dishait.cn/api/v1/postclass/1/post/'+page,
    method: 'GET',
    success: function(res){
     
     
     _self.loadingText = '';
     if(res.data == null){
     
     
		 //在当前页面隐藏导航条加载动画。
      uni.hideNavigationBarLoading();
      _self.loadingText = '已加载全部';
      return false;
     }
     page++;
     console.log(res);
     _self.newsList = _self.newsList.concat(res.data.data.list);
     _self.loadingText = '加载更多';
     uni.hideNavigationBarLoading();
    }
   });
  },
  getnewsList(){
     
     
   page = 1;
   uni.showNavigationBarLoading();
   uni.request({
     
     
    url: `https://ceshi2.dishait.cn/api/v1/postclass/1/post/${
       
       page}`,
    method: 'GET',
    success: function(res){
     
     
		console.log(res)
     page++;
     _self.newsList = res.data.data.list;
     uni.hideNavigationBarLoading();
     uni.stopPullDownRefresh();
     _self.loadingText = '加载更多';
    }
   });
  }
 }
}
</script>
<style>
	.box{
     
     
		width: 100vw;
		height: 100vh;
	}
	.item{
     
     
		width: 100vw;
		height: 200rpx;
		border: 1rpx solid gray;
		text-align: center;
		line-height: 200rpx;
	}
	.loading{
     
     
		text-align: center;
		color: #8F8F94;
	}
</style>

效果如图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43638968/article/details/109056821
今日推荐