小程序上滑触底加载更多数据(请求分页效果)

实现小程序上滑触底加载更多 (分页思想----)

1.组件代码(load-more文件)

load-more / index.wxml

<!-- isLogin判断是否授权登录,showThis默认一开始是不显示组件的 -->
<view hidden='{{!isLogin}}'>
    <view class="loadmore" hidden='{{!showThis}}' bindtap='clickLoadMore'>
        <!-- 图标加载 -->
        <image class="icon {{showIcon?'active':''}}" src='../../images/loading.png'  			  hidden='{{!showIcon}}' />
        <!-- 文字显示 -->
        <text>{{text}}</text>
    </view>
</view>

load-more / index.js

// components/load-more/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
      hasMore: {
        type: Boolean,
        value: false
      },
      // 加载中的显示文本
      loadingText: {
        type: String,
        value: '数据加载中...'
      },
      // 加载失败的显示文本
      failText: {
        type: String,
        value: '数据加载失败, 请点击重试!'
      },
      // 没有更多后的显示文本, 默认没有则隐藏加载更多控件
      finishText: {
        type: String,
        value: ''
      },
      // 列表渲染延时默认给500 ms
      listRenderingDelay: {
        type: Number,
        value: 500
      },
      isLogin:{
        type: Boolean,
        value: false
      }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showThis: false,
    text: '',
    showIcon: false,
    isLoading: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //加载更多的入口方法,
    loadMore: function() {
      if(!this.properties.hasMore){
        console.log('数据加载完成 ...')
        // wx.showToast({
        //   title: '数据已加载完...',
        //   icon:'success',
        //   duration: 2000
        // })
        return
      }
      if(this.data.isLoading) {
        // wx.showToast({
        //   title: '正在加载数据...',
        //   icon:'loading',
        //   duration: 2000
        // })
        console.log('正在加载数据 ...');
        return
      }
      this.setData({
        isLoading: true
      })
      // 向父组件通信
      this.triggerEvent('loadMoreListener')
    },
    
    //加载完成, 传入hasMore 
    loadMoreComplete: function(hasMore) {
        var text = '', showThis = false, showIcon = false
        if (hasMore) {
          showIcon = true
          showThis = true
          text = this.properties.loadingText
        } else if (this.properties.finishText.length>0) {
          text = this.properties.finishText
          showThis = true
        }
        this.setData({
          hasMore: hasMore,
          text: text,
          showIcon: showIcon,
          showThis: showThis
        })
        //界面渲染延迟, 避免列表还未渲染完成就再次触发 loadMore 方法
        setTimeout(function(){
          this.setData({
            isLoading: false
          })
        }.bind(this), this.properties.listRenderingDelay)
    },

    // 加载失败
    loadMoreFail: function() {
      this.setData({
        showIcon: false,
        text: this.properties.failText
      })
      //界面渲染延迟, 避免列表还未渲染完成就再次触发 loadMore 方法
      setTimeout(function(){
        this.setData({
          isLoading: false
        })
      }.bind(this), this.properties.listRenderingDelay)
    },

    //点击 loadmore 控件时触发, 只有加载失败时才会进入页面回调方法
    clickLoadMore: function() {
      if(this.data.text != this.properties.failText) return
      this.setData({
        showIcon: true,
        text: this.properties.loadingText,
        isLoading: true
      })
      this.triggerEvent('clickLoadMore')
    }
  }
})

load-more / index.wxss

/* components/load-more/index.wxss */
.loadmore {
    height: 35px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }  
  
  .loadmore text{
    font-size: 13px;
    color: #bfbfbf;
    font-weight: bold;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  }

  .icon{
    width: 25px;
    height: 25px;
    margin-right: 10px;
  }

  .active {
    animation: loading_animation 0.6s steps(12, end) infinite;
  }
  /* 加载动画*/
  @keyframes loading_animation {
    0% {
      transform: rotate3d(0, 0, 1, 0deg);
    }
    100% {
      transform: rotate3d(0, 0, 1, 360deg);
    }
  }

2.父组件中使用(引入组件的json文件就不给了)

1.index.wxml (在数据列表结构的最下方)

<load-more id="loadMoreView" hasMore="{{hasMore}}" isLogin="{{isLogin}}" bind:loadMoreListener='loadMoreListener' bind:clickLoadMore='clickLoadMore'></load-more>

2.index.js中

// page是全局定义的变量,默认是0
let page = 0
// onLoad()中获取子组件元素
loadMoreView = this.selectComponent("#loadMoreView")// 获取下拉触底加载更多组件
// 上滑触底函数中
	onReachBottom() {
		// 调用子组件事件,加载更多数据
		loadMoreView.loadMore()
	},
// 数据列表分页加载更多
	loadMoreListener() {
		page += 1
		this.setData({
			skipCount: maxResultCount * page
		})
		this.getMyProjects() //请求数据函数
	},
// 获取数据列表的函数中

// 获取列表
	getMyProjects(obj) {
		let data = {
			maxResultCount,
			searchType: this.data.searchType,
			skipCount: obj ? obj.skipCount : this.data.projectsList.length,
			content: this.data.inputGroupNameValue,
			page,
		};
		PostUserGroupList(data)
			.then((res) => {
				console.log('是否重新请求列表');
				// page是从0开始的,如果最后跳转的数量大于数据总数
				if (this.data.skipCount < (res.totalCount - maxResultCount) && maxResultCount < res.totalCount) {
					this.setData({
						hasMore: true //true时表明还有更多的数据
					})
				} else {
					this.setData({
						hasMore: false //false时表明没有下一页数据了
					})
				}
				let projectsList_list = this.data.projectsList
				let list = res.items || [];
				list.forEach((item) => {
					item.IsRead = false;
					item.itemHeight = 0;
					item.creationTime = app
						.moment(item.creationTime)
						.format('YYYY-MM-DD');
				});
				list = setUnreadMessage(list);
				if (page == 0) {
					projectsList_list = list
					wx.stopPullDownRefresh()
				} else {
					projectsList_list = projectsList_list.concat(list)
				}
				this.setData({
					projectsList: projectsList_list,
				});
				console.log(this.data.projectsList, '首页列表数据----');
				// 如果第一页请求的数量
				wx.setStorageSync('projectList', this.data.projectsList);
				// 调用子组件的加载完成事件
				loadMoreView.loadMoreComplete(this.data.hasMore)
				// 获取元素高度
				this.setListEventHeight();
			})
			.catch((err) => {
				if (page != 0) {
				    // 调用子组件的加载失败事件
					loadMoreView.loadMoreFail()
				}
			});
	},
 // 父组件中的点击加载图标时重新加载数据
// 数据加载失败时,点击重新加载
	clickLoadMore() {
		this.getMyProjects() //请求数据
	},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值