当前位置:   article > 正文

微信小程序 封装公共的异步请求_微信小程序公共方法挂载在this上

微信小程序公共方法挂载在this上

1.新建一个文件夹 utils
2.新建 文件 request.js
在这里插入图片描述
在代码中使用:

const res = await this.request({}) //  res = 接口返回值的  message属性  { message,meta }
  • 1

4.如何将封装好的request挂载到 this上 vue的一个实例
1.找到main.js
2.通过原型来挂载

Vue.prototype.request= request;
  • 1

5.封装好的代码!

/* 
1 发送前显示等待中 
2 请求回来了 关闭等待中 
3 封装公共的url 
 */


//  接口的公共的前缀
const BaseURL = "https://api-hmugo-web.itheima.net/api/public/v1";

const request = (config) => {

  uni.showLoading({
    title: "加载中",
    mask: true
  });

  return new Promise((resolve, reject) => {
    wx.request({
      ...config,
      url: BaseURL + config.url,
      success: (result) => {
        // console.log(result);
        if (result.statusCode === 200 && result.data.meta.status === 200) {
          // result.statusCode 表示网络没有问题
          // result.data.meta.status 表示 后台接收到了请求 也返回了正确的数据  
          resolve(result.data.message);
        } else {
          reject(result);
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        uni.hideLoading();
      }
    });
  })
}

const requestAll = async (arr) => {
  uni.showLoading({
    title: "加载中",
    mask: true
  });
  await Promise.all(arr);
  uni.hideLoading();

  return Promise.resolve();
}

export default {
  request,
  requestAll
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/294644
推荐阅读
相关标签
  

闽ICP备14008679号