axios的二次封装
1
|
npm i axios // 下载axios |
首先创建两个文件夹在src目录下;api和config
先在config文件夹下建立一个index.js;具体代码如下:
1
2
3
4
5
6
|
export default { baseUrl:{ dev: "http://localhost:8082/mhy" , //开发环境 pro: "http://xxx.xx.xx.xx:8082/mhy" , //上线环境 } } |
当然我这里是因为我主要写后端springboot,就没有使用什么第三方前端的请求工具
在api文件夹下建立一个axios.js;对axios进行二次封装;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
import axios from "axios" import config from "@/config" // const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev:config.baseUrl.pro const baseUrl = config.baseUrl.pro class HttpRequest{ //构造器 constructor(baseUrl){ this .baseUrl = baseUrl } //请求路径设置 getInsideConfig(){ const config = { baseURL: this .baseUrl, Header:{} } return config } //添加拦截器 interceptors(instance){ // 添加请求拦截器 instance.interceptors.request.use( function (config) { // 在发送请求之前做些什么 const token = localStorage.getItem( "Accept-Token" ); if (token !== null && token !== "" ){ config.headers[ "Accept-Token" ] = token; } return config; }, function (error) { // 对请求错误做些什么 // console.log('添加请求拦截器 请求错误') return Promise.reject(error); }); // 添加响应拦截器 instance.interceptors.response.use( function (response) { // 对响应数据做点什么 // console.log('添加请求拦截器 响应') return response; }, function (error) { // 对响应错误做点什么 // console.log('添加请求拦截器 响应错误') return Promise.reject(error); }); } // 二次封装的请求 request(options) { const instance = axios.create() options = {... this .getInsideConfig(),...options} this .interceptors(instance) return instance(options) } } export default new HttpRequest(baseUrl) |
最后在api文件夹下创建你需要调用的api,当然你可以写在一个里面,也可以不同模块分开写
我这里是分开写的:
然后看看具体怎么使用
fileApi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import axios from "./axios" ; // 上传文件图片 export const uploadImgAPI = (param) => { return axios.request({ url: `/uploadImg/${param.id}`, method: "post" , data: param.formData }) } // 删除一个文件 export const deleteImgAPI = (param) => { return axios.request({ url: `/deleteImg`, method: "post" , data: param }) } |
简单的写一个;在组件中引入就可以使用了
1
|
import { deleteImgAPI, uploadImgAPI } from '@/api/fileApi' |
当然最后你也可以全局注册一下,然后直接通过proxy调用,也很方便,
到此这篇关于vue axios二次封装的详细解析的文章就介绍到这了,更多相关vue axios二次封装内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/shuisanya/p/16630320.html