小程序之上拉加载和下拉刷新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yhflyl/article/details/86167952

创建Data

/**
 * 页面的初始数据
 */   
data: {
    articleInfo: [],
    // 请求数据是否为空的状态    
    flag: true,
    // 初始为第一页    
    index: 1,
},

分页请求数据

 /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getArticleInfo(this.data.index);
  },
  
  getArticleInfo: function(index){
    // 在回调函数中返回请求的数据  
    playModel.getAll({
      index: index,
      success: (res) => {
        let newArticleInfo = res.object;
        // 请求数据为空,不请求  
        if(newArticleInfo.length == 0){
          // 修改请求状态位 false  
          this.setData({flag: false});
          wx.showToast({
            title: '已经到底~~',
            icon: 'loading',
            duration: 2000
          })
        }else{
          // 将请求的数据添加的原来的articleInfo中  
          let articleInfo = this.data.articleInfo.concat(newArticleInfo);
          this.setData({ articleInfo });
        }
      }
    })
  },

上拉刷新

 /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.flag){
      // 页数加一  
      let index = this.data.index + 1;
      // 更新当前页  
      this.setData({index})
      // 发送请求  
      this.getArticleInfo(index);
    }else{
      wx.showToast({
        title: '已经到底~~',
        icon: 'loading',
        duration: 2000
      })
    }
  },

下拉刷新

 /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 初始化页面数据  
    this.setData({
      articleInfo: [],
      index: 1,
      flag: true
    })
    // 发送请求  
    this.getArticleInfo(this.data.index);
  },

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/86167952