vue3+ts+setup获取全局变量getCurrentInstance

前言:

        vue3的 setup中是获取不到this的,为此官方提供了特殊的方法,让我们可以使用this,达到我们获取全局变量的目的,但是在使用typescript的时候,就会有一些新的问题产生,这里来做一个整理。

vue3官方提供的方法

1、引入方法

import { getCurrentInstance } from 'vue'

2、定义变量,接到我们的方法

setup() {
    const { proxy } = getCurrentInstance()
}

3、main.js中定义我们的全局变量

app.config.globalProperties.$api = '111'

4、页面中使用我们的全局变量

setup() {
    const { proxy } = getCurrentInstance()
    console.log(proxy.$api)
}

vue3+ts 使用官方方法遇到的问题:

Property 'proxy' does not exist on type 'ComponentInternalInstance | null'

 我在网上找的方法:网上资料入口

import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加断言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

效果:不识别这种写法,不清楚是什么问题。多方尝试无果

最终我解决问题的方法:

        我把类型换成any,结果成功了,不知道原因,以后在查查资料

setup() {
   const { proxy } = getCurrentInstance() as any
}

 

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值