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
}

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/122997704