vue3 全局注册app.config.globalProperties, 如何处理getCurrentInstance 上下文线上环境报错

在Vue3中,通过app.config.globalProperties全局注册属性和方法。然而,使用getCurrentInstance在组件中获取全局上下文时,可能会在线上环境中报错。官方文档提供了正确的方法来解决这个问题。在main.js中正确配置,并在组件内使用,经过测试线上环境运行正常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue3挂载全局属性和方法,使用app.config.globalProperties, 但是在组件中获取全局上下文的时候getCurrentInstance会在线上环境报错。
搜索了一遍,看了好多文章,都是在本地环境getCurrentInstance有用,线上环境报错,所以一切的一切还是去官网查找,得到最后的完美结果。

线上环境正确使用:

const instance = getCurrentInstance()
 console.log('instance???', instance.appContext.config.globalProperties)

以下方式本地环境有效,线上环境会报错,不建议使用

const { ctx } = getCurrentInstance();
console.log(ctx, "ctx");
// **这样在本地环境可以, 但是线上环境会报错**

线上环境正确的做法是以下操作,亲测试有效:

main.js中

import { createApp } from "vue";
import App from "./App.vue";
// 初始化
import push from '@/utils/push'
import api from '@/utils/api'

const app = createApp(App)
app.config.globalProperties.$asyncPost = api.nextPost
app.config.globalProperties.$push = push


app
  .mount("#app");

页面中加入:

<template>
  <div class="container">
    <div>获取全局</div>
  </div>
</template>

<script>
import { getC
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值