首頁  >  文章  >  微信小程式  >  微信小程式頁面滑動螢幕載入資料的實例詳解

微信小程式頁面滑動螢幕載入資料的實例詳解

黄舟
黄舟原創
2018-05-29 15:00:155400瀏覽

這篇文章主要為大家詳細介紹了微信小程式頁面滑動螢幕載入資料效果,具有一定的參考價值,有興趣的夥伴們可以參考一下

滑動螢幕載入資料是任何小程式中都會用到的功能,本文我將這個功能整理給大家,希望對大家有意。我們先來看看效果圖:

建立目錄

#首先我們現在專案中建立資訊目錄,以下是我自己創建的目錄,大家可以依照自己的需求創建。如圖所示:

建立lists.js檔案

以下是lists.js程式碼

var app = getApp()
Page({
 data: {
  newsList: [],
  lastid: 0,
  toastHidden: true,
  confirmHidden: true,
  isfrist: 1,
  loadHidden: true,
  moreHidden: 'none',
  msg: '没有更多文章了'
 },
 loadData: function (lastid) {
  //显示出加载中的提示
  this.setData({ loadHidden: false })
  var limit = 10
  var that = this
  wx.request({
   url: 'http://127.0.0.1:9090/hpm_bill_web/news/getnewslist', //数据接口
   data: { lastid: lastid, limit: limit },
   header: {
    'Content-Type': 'application/json'
   },
   success: function (res) {
    if (!res.data) {
     that.setData({ toastHidden: false })
     that.setData({ moreHidden: 'none' })
     return false
    }
    var len = res.data.length
    var oldLastid = lastid
    if(len != 0) {
     that.setData({ lastid: res.data[len - 1].id })
    } else {
     that.setData({ toastHidden: false})
    }
    var dataArr = that.data.newsList
    var newData = dataArr.concat(res.data);
     if (oldLastid == 0) {
      wx.setStorageSync('CmsList', newData)
     }
    that.setData({ newsList: newData })
    that.setData({ moreHidden: '' })
   },
   fail: function (res) {
    if (lastid == 0) {
     var newData = wx.getStorageSync('CmsList')
     if(newData) {
      that.setData({ newsList: newData })
      that.setData({ moreHidden: '' })
      var len = newData.length
      if (len != 0) {
       that.setData({ lastid: newData[len - 1].id })
      } else {
       that.setData({ toastHidden: false })
      }
      console.log('data from cache');
     }
     } else {
      that.setData({ toastHidden: false, moreHidden: 'none', msg: '当前网格异常,请稍后再试' })
     }
   },
   complete: function () {
    //显示出加载中的提示
    that.setData({ loadHidden: true })
   }
  })
 },
 loadMore: function (event) {
  var id = event.currentTarget.dataset.lastid
  var isfrist = event.currentTarget.dataset.isfrist
  var that = this
  wx.getNetworkType({
   success: function (res) {
    var networkType = res.networkType // 返回网络类型2g,3g,4g,wifi
    if (networkType != 'wifi' && isfrist == '1') {
     that.setData({ confirmHidden: false })
    }
   }
  })
  this.setData({ isfrist: 0 })
  this.loadData(id);
 },
 onLoad: function () {
  var that = this
  this.loadData(0);
 },
 toastChange: function () {
  this.setData({ toastHidden: true })
 },
 modalChange: function () {
  this.setData({ confirmHidden: true })
 }
})

建立頁面檔案(lists.wxml)