利用async + await封装uni-app网络请求

// /common/requeat.js
var url = "请求域名"
// option           ========>  object
// option.url       =>    url地址               =>     string                             =>    必填
// option.method    =>    请求方式,            =>      string 取值 GET POST 默认POST      =>    选填
// option.header    =>    请求header头          =>      object                            =>    选填
// option.data      =>    请求参数              =>      object                            =>    选填
// option.loading   =>    是否显示加载动画       =>      boolean 取值true false 默认false   =>    选填
// option.loadtext  =>    加载提示语            =>       string  默认 加载中...            =>    选填
// option.msg       =>    请求失败提示语        =>       string  不穿即不显示 默认空       =>     选填

export default class api {
  syncRequest = function(option) {
    option.method = option.method ? option.method : "POST"
    option.header = option.header ? option.header : {}
    option.data = option.data ? option.data : {}
    option.loading = option.loading ? true : false,
    option.loadtext = option.loadtext ? option.loadtext : '加载中...'
    if (option.method == "GET") {
      option.header['Content-Type'] = 'application/json;charset=UTF-8'
    } else {
      option.header['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    if (option.loading) {
      uni.showLoading({
        mask: true,
        title: option.loadtext
      })
    }
    return new Promise((resolve, reject) => {

      uni.request({
        url: url + option.url,
        method: option.method,
        header: option.header,
        data: option.data,
        success: (res) => {
          if (option.loading) {
            uni.hideLoading()
          }
          if (res.statusCode == 200) {            
            resolve(res);            
          } else {
            if (option.msg) {
              uni.showToast({
                icon: "none",
                title: option.msg
              })
            }
          }

        },
        fail: (err) => {
          if (option.loading) {
            uni.hideLoading()
          }
          if (option.msg) {
            uni.showToast({
              icon: "none",
              title: option.msg
            })
          }
          reject(err)
        }
      });
    })
  }
}
//main.js
import Request from './common/request.js'
let request = new Request()
Vue.prototype.$api = request
//index.vue

<button type="default" @tap="request">点击</button>

async request(){
  var data = await this.$api.syncRequest({
  	//除了url必填其他都是选填
    url:'/index/index/index',//接口
    loading:true,//显示加载图
  })
  console.log(data);
},
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值