在vue2
中会习惯性的把axios
挂载到全局,以方便在各个组件或页面中使用this.$http
请求接口。但是在vue3
中取消了Vue.prototype
,在全局挂载方法和属性时,需要使用官方提供的globalProperties
API。
一、全局挂载
- 在
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' |
| |
| |
| |
| |
| Vue.prototype.$http = Axios; |
| Vue.prototype.$utils = Utils; |
| |
| |
| 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) |
| |
| |
| app.config.globalProperties.$http = Axios |
| app.config.globalProperties.$utils = Utils |
| |
| |
| app.use(router).use(store); |
| app.mount('#app') |
二、全局使用
| <script> |
| export default { |
| data() { |
| return { |
| list: [] |
| } |
| }, |
| mounted() { |
| this.getList() |
| }, |
| methods: { |
| getList() { |
| this.$http({ |
| url: '/api/v1/posts/list' |
| }).then(res=>{ |
| let { data } = res.data |
| this.list = data |
| }) |
| }, |
| }, |
| } |
| </script> |
- 在
vue3
的setup
中使用getCurrentInstance
API获取全局对象:
| <template> |
| <div class="box"></div> |
| </template> |
| <script> |
| import { ref, reactive, getCurrentInstance } from 'vue' |
| export default { |
| setup(props, cxt) { |
| |
| const currentInstance = getCurrentInstance() |
| const { $http, $message, $route } = currentInstance.appContext.config.globalProperties |
| |
| function getList() { |
| $http({ |
| url: '/api/v1/posts/list' |
| }).then(res=>{ |
| let { data } = res.data |
| console.log(data) |
| }) |
| } |
| |
| |
| |
| const { proxy } = getCurrentInstance() |
| |
| function getData() { |
| proxy.$http({ |
| url: '/api/v1/posts/list' |
| }).then(res=>{ |
| let { data } = res.data |
| console.log(data) |
| }) |
| } |
| |
| |
| } |
| } |
| </script> |
- 方法一:通过
getCurrentInstance
方法获取当前实例,再根据当前实例找到全局实例对象appContext
,进而拿到全局实例的config.globalProperties
。
- 方法二:通过
getCurrentInstance
方法获取上下文,这里的proxy
就相当于this
。
提示: 可以通过打印getCurrentInstance()
看到其中有很多全局对象,如:$route
、$router
、$store
。如果全局使用了ElementUI
后,还可以拿到$message
、$dialog
等等。
《Vue3学习与实战》系列
欢迎访问:天问博客
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了