个人学习笔记:
在发送请求时,不想每次发送一个请求都要重复写接口地址,接口请求uni.request(),过于繁琐。
1.创建api.js封装所有的请求接口地址
//baseurl
const baseurl = 'http://localhost:3000/api/'
//方法一
// class apiUrl{
// static urls(){
// let getAllCategory=`${baseurl}getAllCategory`
// return {
// getAllCategory,
// }
// }
// }
//方法二
let apiUrl = function() {
// 请求菜品分类
let getAllCategory = `${baseurl}getAllCategory`
return {
getAllCategory,
}
}
export {apiUrl}
2.创建request.js封装uni.request请求
// Get 请求
let getRequest = function(urls) {
return new Promise((resolve, reject) => {
uni.request({
url: urls,
method: "GET",
success: (res) => {
resolve(res.data)
},
})
})
}
//发送Post请求
export { getRequest }
3.可以在需要引入的组件中部分引入,也可以在main.js文件中全局引入
(1)main.js中引入
// 全局url地址
import {apiUrl} from './api/api.js'
Vue.prototype.ApiUrl = apiUrl
//全局get请求
import {getRequest} from './api/request.js'
Vue.prototype.GetRequest=getRequest
使用:
// 请求全部菜品分类
async getCatagory(){
// 接口地址
let url=this.ApiUrl().getAllCategory
console.log(url);
// 发送请求
let res=await this.GetRequest(url)
console.log(res);
}
结果:
(2)在需要的地方引入,局部引入
引入、使用:
扫描二维码关注公众号,回复:
15825523 查看本文章
import {getRequest} from '../../api/request.js'
import {apiUrl} from '../../api/api.js'
export default{
data(){
return{
}
},
methods:{
// 请求全部菜品分类
async getCatagory(){
// 接口地址
let url=apiUrl().getAllCategory
console.log(url);
// 发送请求
let res=await getRequest(url)
console.log(res);
}
},
onLoad() {
// 请求全部菜品分类
this.getCatagory()
// 请求全部菜品信息
}
}
结果: