小程序封装上拉加载和下拉刷新

封装在公用的js文件里

// resList.js
const app = getApp()
module.exports = Behavior({
  behaviors: [],
  properties: {},
  data: {
    list: [], //列表数据
    recordCount: 0, //列表总条数
    pageNo: 1,
    pageSize: 20
  },
  methods: {
    // 参数
    _requestPageList(callback) {
      // let opt = {
      //   type: 1, //(主要是和礼品管理共享接口区别排序)
      //   isValid: 1, //(是否有效,1是2否)此处默认填写1,只有有效期内的才能再礼品列表展示
      //   name: ""
      // }
      // this._requestPageListCom("giftPageList", opt, callback);
    },
    // 列表接口
    _requestPageListCom(url, params, callback) {
      let opt = Object.assign({}, params, {
        pageData: {
          pageNo: this.data.pageNo,
          pageSize: this.data.pageSize
        },
      })
      app.$request.post(app.$config[url], opt).then(res => {
        if (res.returnResult === 200) {
          const oldList = this.data.list
          const newGoodsList = res.returnData.data
          const nList = [...oldList, ...newGoodsList]
          let newData = {}; //新变更数据
          for(let i in nList){
            newData['list['+i+']'] = nList[i]
          }
          this.setData(newData);//赋值列表数据
          this.setData({
            recordCount: res.returnData.recordCount
          })
          if(callback && typeof callback === 'function'){
            callback()
          }
        }
      })
    },
    // 下拉刷新
    onPullDownRefresh() {
      this.setData({
        list: [],
        pageNo: 1
      });
      this._requestPageList(() => {
        // 当处理完数据刷新后,wx.stopPullDownRefresh可以停止当前页面的下拉刷新
        wx.stopPullDownRefresh();
      });
    },
    // 上拉加载
    onReachBottom(){
      let _self = this;
      if (this._freshing || _self.data.list.length >= _self.data.recordCount || _self.data.recordCount === 0) return
      this._freshing = true;
      this.setData({
        pageNo: ++_self.data.pageNo
      });
      this._requestPageList(() => {
        _self._freshing = false;
      });
    },
  }
})
页面引用

let resListCom = require('../../mixins/resList')

Page({
  behaviors: [resListCom],
  data: {
    
  },
  onLoad: function () {
    this._requestPageList()
  },
  _requestPageList(callback) {
    let opt = {
      id: wx.getStorageSync('virtualUserID')
    }
    // 第一个参数是请求的接口名
    this._requestPageListCom("virtualIntegral", opt, callback);
  },
})

猜你喜欢

转载自www.cnblogs.com/lijh03/p/12929900.html