商城系統(tǒng) 注冊

小程序之上拉刷新下拉加載的實(shí)現(xiàn)

2020-09-27|HiShop
導(dǎo)讀:小程序上拉刷新,下拉加載是很基本的效果,如何實(shí)現(xiàn)可以減少代碼量。...

  小程序之上拉刷新下拉加載的實(shí)現(xiàn)

  上拉刷新,下拉加載,分別點(diǎn)擊tab都還能夠請求服務(wù)器。我想的最好的方法是把日期和月份這2個抽離出來做成一個方法,然后上拉刷新,下拉加載,點(diǎn)擊tab分別調(diào)用日期和月份方法即可。我嘗試百度/google,見到最多的鏈?zhǔn)綄懛?,以獲取用戶數(shù)據(jù)舉例:

  //這里的操作都是舉例說明。

  wxLogin()

  .then(=>res{

  console.log(res.code)

  return wxRequest.getUserOpenId(url, params)//請求獲取用戶ID

  })

  .then(=>res{

  console.log(res.openId)

  return wxRequest.getUserPhone());//請求獲取用戶手機(jī)

  })

  .catch()

  在index.js頁面 ; getUserOpenId()和getUserPhone()都是封裝在另外一個js里面的。或者是直接getUserMessage().then(res=>).catch();這樣直接獲取用戶數(shù)據(jù)了。

  wxRequest.getUserMessage()

  .then(=>res{

  console.log(res.code);

  })

  .catch()

  當(dāng)然我這樣舉例還是不能說明存在什么問題,那么如果我要像上面圖那樣獲取日期數(shù)據(jù),月份數(shù)據(jù)怎么辦呢?難道按照第一個那樣寫,上拉加載那里寫一堆,下拉刷新那里一堆,切換tab也寫一堆重復(fù)的代碼?還是說我管你是上拉刷新,還是下拉加載好,我直接通過一個接口在一起獲取數(shù)據(jù)?所以我通過百度/google到他們寫的還不夠完善(不是寫的不好哈)

  我的寫法:

小程序之上拉刷新下拉加載的實(shí)現(xiàn)

  //我只是抽取我部分代碼來展示

  Page({

  data:{

  },

  onLoad: function () {//生命周期

  this.readUserMesage();

  },

  readUserMesage(): function () {//獲取用戶信息,并獲取按日期的數(shù)據(jù)

  this.showLoading();

  let parameters = 'user?ptId=aaaaaaaaaaaaaa';

  api.getRequest({

  parameters: parameters,

  }).then(res => {

  return this.readDayData(); //獲取日期信息

  }).catch(error => {

  this.hideLoading();

  });

  },

  readMonthData() {//把月份單獨(dú)抽取出來

  var url = 'dailypay?xxxxx=aaaa&yyy=bbbbbb';

  var parameters = { parameters: url }

  return api.getRequest(parameters)//我這里是封裝請求服務(wù)器的,注意我加了return

  .then(res => {

  //這里就可以獲取到返回的res的集合數(shù)據(jù)

  }).catch(error => {

  console.log(JSON.stringify(error));

  this.hideLoading();

  });

  },

  readDayData() {//把日期單獨(dú)抽取出來

  var url = 'dailypay?xxxxx=aaaa&yyy=bbbbbb';

  var parameters = { parameters: url }

  return api.getRequest(parameters)//我這里是封裝請求服務(wù)器的,注意我加了return

  .then(res => {

  //這里就可以獲取到返回的res的集合數(shù)據(jù)

  }).catch(error => {

  this.hideLoading();

  });

  },

  onPullDownRefresh() {//下拉刷新

  if (this.data.currentIndex == 0) {//如果當(dāng)前是在日期

  this.readDayData();

  } else {//如果當(dāng)前是在月份

  this.readMonthData();

  }

  },

  onReachBottom() {//上拉加載

  if (this.data.currentIndex == 0) {

  this.readDayData();

  } else {

  this.readMonthData();

  }

  },

  )}

  好了,我的方法介紹完成了。這樣做就可以減少代碼量了。
 

HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。

更多小程序開發(fā)案例,盡在:http://descansotropical.com/xiaocx/kaifa.html 

電話咨詢 預(yù)約演示 0元開店