vue3定义全局变量

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3定义全局变量

想想就很棒   2022-09-28 我要评论

vue3定义全局变量

在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

vue3全局变量app.config.globalProperties的使用

globalProperties

  • 类型:[key: string]: any
  • 默认:undefined
  • 用法

添加一个可以在应用的任何组件实例中访问的全局 property。组件的 property 在命名冲突具有优先权。

这可以代替 Vue 2.x Vue.prototype 扩展:

// 之前(Vue 2.x)
Vue.prototype.$http = () => {}
 
// 之后(Vue 3.x)
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

当我们想在组件内调用http时需要使用getCurrentInstance()来获取。

import { getCurrentInstance, onMounted } from "vue";
export default {
  setup( ) {
    const { ctx } = getCurrentInstance(); //获取上下文实例,ctx=vue2的this
    onMounted(() => {
      console.log(ctx, "ctx");
      ctx.http();
    });
  },
};

getCurrentInstance代表上下文,即当前实例。ctx相当于Vue2的this, 但是需要特别注意的是ctx代替this只适用于开发阶段,如果将项目打包放到生产服务器上运行,就会出错,ctx无法获取路由和全局挂载对象的。此问题的解决方案就是使用proxy替代ctx,代码参考如下。

import { getCurrentInstance } from 'vue'
export default ({
  name: '',
  setup(){
    const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因为ctx只在开发环境有效
    onMounted(() => {
      console.log(proxy, "proxy");
      proxy.http();
    });
  }
})

注意:尤大在vue3推荐使用依赖注入:provide和inject。原因:vue/rfcs.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们