导出一个方法,在fetch文件里
1.引入axios
import axios from 'axios'
2.封装axios
export default async(url='',data={},method='post')=>{
if(process.env.NODE_ENV !== 'development'){
url = 'biyao/public' +url; //线上得前缀路径
}
return new Promise((resolove,reject)=>{
axios({
url,
data,
method
}).then(resObj=>{
resolve(resObj['data'])
}).catch(err=>{
})
})
}
再封装一个网络请求api
1,引入刚刚封装的axios方法
import fetch from '@utils/fetch'
2.导出方法
export const homePageCommand = (data,loading)=>fetch('/api/firstCategory',data)
3.使用这个方法
//1.
mouted(){
//定义一个方法
this.getData()
}
//2.
methods:{
async getData(){
await homePageCommand ().then(res=>{
})
}
}
本文介绍了一种封装Axios库的方法,用于简化HTTP请求流程。通过自定义fetch函数,实现了对线上环境URL前缀的自动添加,并通过Promise处理异步响应。此外,还展示了如何进一步封装网络请求API,以便于在项目中重复使用。
664

被折叠的 条评论
为什么被折叠?



