const BASE_URL = ‘‘
let ajaxTime = 0
export const myRequest = (option) => {
ajaxTime++
uni.showLoading({
title: "加载中",
mask: true
})
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + option.url,
method: option.mehtod || ‘GET‘,
data: option.data || {},
success: (res) => {
if (res.statusCode !== 200) {
return uni.showToast({
title: "获取失败"
})
}
resolve(res)
},
fail: (err) => {
uni.showToast({
title: ‘请求接口失败‘
})
reject(err)
},
complete: () => {
ajaxTime--
if (ajaxTime == 0) {
uni.hideLoading()
//防止同一页面请求多个数据时加载框异常
}
}
})
})
}
然后在main.js中将封装好的工具组件全局引用
import {myRequest}from ‘utils/request/api.js‘
Vue.prototype.$myRequest=myRequest
小程序接口请求封装