微信小程序学习 下滑刷新、触底上滑刷新

入门学习使用的是测试号。由于访问了https地址获取数据,需要如图设置:

微信小程序学习 下滑刷新、触底上滑刷新_第1张图片

下拉刷新需要在app.json中配置:

"enablePullDownRefresh": true

joke.wxml代码如下,对应的wxss文件就看个人喜好了,对于text对应的class,只设置了width:90%,不让文字靠近屏幕边侧:


  {
    {joke}}

 

对应的joke.js代码如下,注释应该很清楚了:

下滑刷新数据,触底时上滑刷新数据。

Page({
  data: {
    joke: "哈哈",
    disabled: false,
    plain: true,
    loading: false,
    jokes: [],//获取的数据
    jokesLength: 0,//获取的数据的长度
    currIndex: 0//当前显示的数据对应的索引
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getJokes();
  },

  /**
   * 触底上拉加载
   */
  onReachBottom: function() {
    this.getNextJoke()
  },

  /**
   * 下拉加载
   */
  onPullDownRefresh: function() {
    this.getNextJoke()
  },

  /**
   * 触底上拉加载和下拉加载
   */
  getNextJoke: function() {
    if (this.data.jokesLength > this.data.currIndex) {
      this.setData({
        joke: this.data.jokes[this.data.currIndex].content,
        currIndex: this.data.currIndex + 1
      })
      this.goTop()
      wx.stopPullDownRefresh() 

    } else {
      this.setData({
        currIndex: 0
      })
      this.getJokes()
      wx.stopPullDownRefresh() 

    }
  },

  /**
   * 回到顶部
   */
  goTop: function(e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      })
    }
  },

  /**
   * 获取笑话
   */
  getJokes: function() {
    var curr = this;
    wx.request({
      url: 'https://zzw1008.github.io/moon/jokes/1.json',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        if (res.statusCode == 200) {
          curr.setData({
            jokes: res.data,
            jokesLength: res.data.length
          })
          if (curr.data.jokesLength > 0) {
            curr.setData({
              joke: curr.data.jokes[curr.data.currIndex].content,
              currIndex: curr.data.currIndex + 1
            })
          }
          curr.goTop()
        } else {
          wx.showModal({
            title: '提示',
            content: '悲剧,获取数据失败'
          })
        }

      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '悲剧,获取数据失败'
        })
      }
    })
  }
})

访问的接口地址:https://zzw1008.github.io/moon/jokes/1.json 是启动了github的pages 功能。建一个public仓库,settings中开启此功能即可预置的json形式数据。

参考地址:

微信小程序官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/

你可能感兴趣的:(微信小程序)