vue3学习与实战 · 全局挂载使用axios

912 阅读1分钟

vue2中会习惯性的把axios挂载到全局,以方便在各个组件或页面中使用this.$http请求接口。但是在vue3中取消了vue.prototype,在全局挂载方法和属性时,需要使用官方提供的globalPropertiesAPI。

image.png 一、全局挂载 提示: 可以通过打印getCurrentInstance()看到其中有很多全局对象,如:routeroute、router、store。如果全局使用了ElementUI后,还可以拿到store。如果全局使用了ElementUI后,还可以拿到message、$dialog等等。

在vue2项目中,入口文件main.js配置Vue.prototype挂载全局方法对象: import vue from 'vue' import router from '@/router' import store from '@vuex' import axios from 'axios' import Utils from '@/tool/utils' import App from './App.vue'

// ...

/* 挂载全局对象 start / vue.prototype.http=axios;vue.prototype.http = axios; vue.prototype.utils = Utils; / 挂载全局对象 end */

new vue({ router, store, render: h => h(App) }).$mount('#app')

在vue3项目中,入口文件main.js配置globalProperties挂载全局方法对象:

import { createApp } from 'vue' import router from './router' import store from './store' import axios from 'axios' import Utils from '@/tool/utils' import App from './App.vue'

// ...

const app = createApp(App)

/* 挂载全局对象 start / app.config.globalProperties.http=axiosapp.config.globalProperties.http = axios app.config.globalProperties.utils = Utils / 挂载全局对象 end */

app.use(router).use(store); app.mount('#app') 二、全局使用

在vue2中使用this.$http

在vue3的setup中使用getCurrentInstanceAPI获取全局对象

}