在vue3中全局挂载axios

本文最后更新于:1 年前

前言

vue3中已经不支持全局挂载properties了,所以通过vue-cli生成的vue3项目,添加了axios库以后,使用插件的方式引入插件,由于vue不再支持根级property,所以会报错。

解决方法

修改axios.js

在/src/plugins/axios.js按照以下方式修改对应的部分:

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
- Plugin.install = function (Vue) {
- Vue.axios = axios;
- Object.defineProperties(Vue.prototype, {
- axios: {
- get() {
- return axios;
- }
- },
- $axios: {
- get() {
- return axios;
- }
- }
- });
-};
- Vue.use(Plugin)
+ let Plugin_axios = {
+ install(app, options) {
+ app.axios = _axios;
+ window.axios = _axios;
+ app.config.globalProperties.$axios = {
+ axios: {
+ get() {
+ return _axios;
+ }
+ },
+ $axios: {
+ get() {
+ return _axios;
+ }
+ },
+ };
+ },
+ version: "1.0.0"
+};

注意:默认的install已经不再支持,所以把Plugin.install删掉,改成Plugin_axios,并且把Plugin_axios放到最后导出。

安装插件

打开/src/main.js,在对应的位置添加如下代码:
导入axios

1
import Plugin_axios from './plugins/axios'

安装插件

1
app.use(Plugin_axios);

这样就完成了

完整代码

axios.js

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
57
58
59
60
"use strict";
import axios from "axios";

// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
// baseURL: process.env.baseURL || process.env.apiUrl || ""
// timeout: 60 * 1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
function(config) {
// Do something before request is sent
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);

// Add a response interceptor
_axios.interceptors.response.use(
function(response) {
// Do something with response data
return response;
},
function(error) {
// Do something with response error
return Promise.reject(error);
}
);

let Plugin_axios = {
install(app, options) {
app.axios = _axios;
window.axios = _axios;
app.config.globalProperties.$axios = {
axios: {
get() {
return _axios;
}
},
$axios: {
get() {
return _axios;
}
},
};
},
version: "1.0.0"
};

export default Plugin_axios;

main.js

1
2
3
4
5
6
7
8
9
10
11
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import Plugin_axios from './plugins/axios'

createApp(App)
.use(router)
.use(store)
.use(Plugin_axios)
.mount('#app')

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!