Silentdoer

导航

Vue3 setup如何使用this.$xxx全局变量

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

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

    首先在main.js里写一个我们要定义的全局变量,比如一个系统id吧(这里$systemId是在data(){..}可以用this.$systemId来使用)

app.config.globalProperties.$systemId = "10"

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

import { getCurrentInstance } from "vue";
const context = getCurrentInstance()?.appContext.config.globalProperties;
const systemId = context?.$systemId;
console.log(systemId);//控制台可以看到输出了10

原文:https://blog.csdn.net/m0_54864585/article/details/123369501(做了一些修改优化)

posted on 2022-12-05 19:45  Silentdoer  阅读(5467)  评论(1编辑  收藏  举报