Vue3中怎么设置全局变量

简介: Vue3中怎么设置全局变量

vue2中设置全局变量:

Vue.prototype.$xxxx=xxx来定义全局变量,然后通过this.$xxx来获取全局变量。

vue3中设置全局变量:

因为vue3中在setup里面我们是无法获取到this的

首先在main.js里写一个我们要定义的全局变量(定义全局方法也一样哦),比如一个系统id吧

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

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

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

这里 getCurrentInstance()?.appContext 就是获得app组件的信息,后面跟的属性都是跟挂载时候的写法一毛一样,所以比较好记


相关文章
|
9天前
vue3【实战】语义化首页布局
vue3【实战】语义化首页布局
28 2
|
9天前
|
存储 容器
vue3【实战】来回拖拽放置图片
vue3【实战】来回拖拽放置图片
17 2
|
9天前
|
JavaScript 开发工具 开发者
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
32 1
|
9天前
|
API
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
Pinia 实用教程【Vue3 状态管理】状态持久化 pinia-plugin-persistedstate,异步Action,storeToRefs(),修改State的 $patch,$reset
18 1
|
9天前
|
JavaScript
vue3 【提效】自动注册组件 unplugin-vue-components 实用教程
vue3 【提效】自动注册组件 unplugin-vue-components 实用教程
17 1
|
3天前
【vue3】Argumnt of type ‘history:RouterHistory;}is not assignable to paraeter of type ‘RouterOptions‘.
【vue3】Argumnt of type ‘history:RouterHistory;}is not assignable to paraeter of type ‘RouterOptions‘.
6 0
|
3天前
|
JavaScript
【vue3】vue3中路由hash与History的设置
【vue3】vue3中路由hash与History的设置
8 0
|
3天前
|
编解码 前端开发
【Vue3】解决电脑分辨率125%、150%及缩放导致页面变形的问题
【Vue3】解决电脑分辨率125%、150%及缩放导致页面变形的问题
11 0
|
3天前
|
JavaScript
【vue】 vue 翻页时钟制作,vue2、vue3
【vue】 vue 翻页时钟制作,vue2、vue3
11 0
|
9天前
vue3 【提效】自动导入框架方法 unplugin-auto-import 实用教程
vue3 【提效】自动导入框架方法 unplugin-auto-import 实用教程
20 0