vue3中怎么实现定义全局变量

广告:宝塔Linux面板高效运维的服务器管理软件 点击【 https://www.bt.cn/p/uNLv1L 】立即购买

vue3中怎么实现定义全局变量

vue3定义全局变量

在vue2中,我们知道vue2.x是使用Vue.prototype.$xxxx=xxx来定义全局变量,然后通过this.$xxx来获取全局变量。

但是在vue3中,这种方法显然不行了。因为vue3中在setup里面我们是无法获取到this的,因此按照官方文档我们使用下面方法来定义全局变量:

首先在main.js里写一个我们要定义的全局变量,比如一个系统id吧

app.config.globalProperties.$systemId = "10"
登录后复制

现在在页面里需要使用这个变量,只需要从vue中引入getCurrentInstance即可,注意不能在页面中使用this.

import { getCurrentInstance } from "vue";const systemId = getCurrentInstance()?.appContext.config.globalProperties.$systemIdconsole.log(systemId);//控制台可以看到输出了10
登录后复制vue3全局变量app.config.globalProperties的使用globalProperties

类型:[key: string]: any

默认:undefined

用法

添加一个可以在应用的任何组件实例中访问的全局 property。组件的 property 在命名冲突具有优先权。

这可以代替 Vue 2.x Vue.prototype 扩展:

// 之前(Vue 2.x)Vue.prototype.$http = () => {} // 之后(Vue 3.x)const app = Vue.createApp({})app.config.globalProperties.$http = () => {}
登录后复制

当我们想在组件内调用http时需要使用getCurrentInstance()来获取。

import { getCurrentInstance, onMounted } from "vue";export default {  setup( ) {    const { ctx } = getCurrentInstance(); //获取上下文实例,ctx=vue2的this    onMounted(() => {      console.log(ctx, "ctx");      ctx.http();    });  },};
登录后复制

getCurrentInstance代表上下文,即当前实例。ctx相当于Vue2的this, 但是需要特别注意的是ctx代替this只适用于开发阶段,如果将项目打包放到生产服务器上运行,就会出错,ctx无法获取路由和全局挂载对象的。此问题的解决方案就是使用proxy替代ctx,代码参考如下。

import { getCurrentInstance } from 'vue'export default ({  name: '',  setup(){    const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因为ctx只在开发环境有效    onMounted(() => {      console.log(proxy, "proxy");      proxy.http();    });  }})
登录后复制

以上就是vue3中怎么实现定义全局变量的详细内容,更多请关注9543建站博客其它相关文章!

广告:SSL证书一年128.66元起,点击购买~~~

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。

作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:了解Node中的事件循环、process.nextTick()
下一篇:laravel注册错误处理

发表评论

关闭广告
关闭广告