【微信小程序】网络请求

79 阅读1分钟

知识点:wx.request()、enablePullDownRefresh开启下拉刷新、页面相关事件处理函数--监听用户下拉动作 onPullDownRefresh() {}、wx.showLoading({title:'加载中...',mask:true})、wx.showNavigationBarLoading()
实现功能:
1.点击刷新图片列表
2.开启下拉刷新,当加载完整停止下拉动效,停止loding
3.开启上拉刷新

 环境:微信小程序开发工具

测试api(随机获取猫咪靓照):api.thecatapi.com/v1/images/s…

示例:

转存失败,建议直接上传图片文件​编辑

完整代码

request.wxml

<button bind:tap="requestBtn" type="primary">网络请求</button>

    <view class="box" wx:for="{{imgArr}}" wx:key="id">
    <text>图片id:{{index+1}}</text>
    <image src="{{item.url}}" mode="widthFix"/>
    </view>
 /* pages/request/request.wxss */
    .box{
      margin: 0 auto;
      text-align: center;
      border: 1px solid red;
      margin-bottom: 25rpx;
    }
/* pages/request/request.json */
{
  "usingComponents": {},
  "backgroundColor":"#2e2e2e",
  "enablePullDownRefresh": true,
  "nReachBottomDistance":200
}
// pages/request/request.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
imgArr:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading()
    this.requestBtn()
  },
  requestBtn(){
    wx.request({
      url: 'https://api.thecatapi.com/v1/images/search?limit=2',
      success:res=>{
    
        wx.stopPullDownRefresh()
        this.setData({
          imgArr:res.data
        })
      // console.log(this.data.imgArr);
      },
      complete:err=>{
      wx.hideNavigationBarLoading()
        wx.hideLoading()
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      imgArr:[]
    })
    this.requestBtn();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.requestBtn()
    wx.showNavigationBarLoading()
    console.log('触底~');
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  
  },
})