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组件的信息,后面跟的属性都是跟挂载时候的写法一毛一样,所以比较好记

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐