前言 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'
安装插件
这样就完成了
完整代码 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" ;let config = { };const _axios = axios.create (config); _axios.interceptors .request .use ( function (config ) { return config; }, function (error ) { return Promise .reject (error); } ); _axios.interceptors .response .use ( function (response ) { return response; }, function (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' )