对uni.request进行二次封装可以增强代码的复用性和维护性
具体步骤如下:
1、项目下新建util文件夹,再创建api.js文件
2、在api.js下写封装代码
api.js参考代码如下
const BASE_URL='https://api-hmugo-web.itheima.net'
export const myRequest = (options)=>{
return new Promise((resolve,reject)=>{
uni.request({
url:BASE_URL+options.url,
method:options.method || 'GET',
data:options.data ||{},
success: (res) => {
//判断获取数据是否成功
if(res.data.status ===0){
return uni.showToast({
title:'获取数据失败'
})
}
//获取成功
resolve(res)
},
fail: (err) => {
uni.showToast({
title:'请求接口失败'
})
reject(err)
}
})
})
}
3、在main.js全局注册
import {myRequest} from './util/api.js'
Vue.prototype.$myRequest = myRequest
4、页面调用
const res = await this.$myRequest({
url:'/api/public/v1/home/swiperdata'
})
console.log(res)