使用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
}补充: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>
总结
到此这篇关于使用vue3+ts+setup获取全局变量getCurrentInstance的文章就介绍到这了,更多相关vue3 ts setup获取全局变量内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
如何使用Vue mapState快捷获取Vuex state多个值
这篇文章主要为大家介绍了如何使用Vue mapState快捷获取Vuex state多个值实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-06-06
在vue使用clipboard.js进行一键复制文本的实现示例
这篇文章主要介绍了在vue使用clipboard.js进行一键复制文本的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-01-01


最新评论