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

sudo0m Lv3

目录

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

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

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

1
app.config.globalProperties.$http = http

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

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

原文:https://blog.csdn.net/m0_54864585/article/details/123369501

作者:Silentdoer

  • 标题: Vue3 setup ts如何使用this.$xxx全局变量
  • 作者: sudo0m
  • 创建于: 2023-08-03 19:23:33
  • 更新于: 2023-08-16 15:45:21
  • 链接: https://sudo0m.github.io/page/20230803192333/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
此页目录
Vue3 setup ts如何使用this.$xxx全局变量