⚡封装uni-app中uni.request()
1、封装uni.request():
//1、首先创建一个工具包utils
//2、创建一个api.js文件
//3、编写api.js内容:
//创建一个常量 conset BASE_URL作为默认url地址
const BEST_URL = 'http://localhost:8080'
export const myRequest = (option)=>{ //将封装好的函数导入出去
return new Promise((resolve,reject)=>{
uni.request({
url:BEST_URL+option.url, //传入url地址
data:option.data || { }, //请求数据
method:option.method || 'GET', //请求方法
success: (res) => { //相应成功回调函数
if (res.data.code !== 201) {
uni.showToast({
title: '获取数据失败!',
icon: 'none',
})
}
resolve(res) // 将请求结果resolve出去
},
fail: (err) => {
uni.showToast({
title:'请求接口失败',
icon:'none',
})
reject(err)
}
})
})
}
2、在main.js 中:
// 在main.js 中
import {myRequist } from "./util/api.js"
Vue.prototype.$myRequist = myRequist //Vue中的'V'要大写!!!
3、应用方法:
methods: {
async getNavigation() {
const res = await this.$myRequest({
url: '/G/queryNavigation'
})
console.log(res)
}
//如需要进入页面便获取数据还应在onload()中声明
onLoad() {
this.getNavigation()
}