在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.$systemId
console.log(systemId);//控制台可以看到输出了10

如果大家还有其他的方法欢迎大家评论区留言或者私信我,希望这篇博客可以帮助到大家。

Logo

前往低代码交流专区

更多推荐