vue3 ts setup获取全局变量

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

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

vue3 ts setup获取全局变量

浩星   2022-09-28 我要评论

前言:

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
}

补充:Vue3 getCurrentInstance与ts结合使用的问题

vue3项目中,如果不用ts这样使用是没问题的

const { proxy } = getCurrentInstance()

在ts中使用会报错:报错:...类型“ComponentInternalInstance | null”

我们在项目中一般会用到很多getCurrentInstance()方法,直接封装一下

创建useCurrentInstance.ts文件:

import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const proxy = appContext.config.globalProperties
    return {
        proxy
    }
}

组件内使用:

<script lang="ts">
import { defineComponent } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
export default defineComponent({
  setup() {
    const { proxy } = useCurrentInstance();
    console.log(proxy);
  },
});
</script>

总结

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

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