Vue3之getCurrentInstance与ts怎么结合使用

其他教程   发布日期:2025年03月24日   浏览次数:149

本篇内容主要讲解“Vue3之getCurrentInstance与ts怎么结合使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue3之getCurrentInstance与ts怎么结合使用”吧!

getCurrentInstance与ts结合使用

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

  1. const { proxy } = getCurrentInstance()

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

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

创建useCurrentInstance.ts文件:

  1. import { ComponentInternalInstance, getCurrentInstance } from 'vue'
  2. export default function useCurrentInstance() {
  3. const { appContext } = getCurrentInstance() as ComponentInternalInstance
  4. const proxy = appContext.config.globalProperties
  5. return {
  6. proxy
  7. }
  8. }

组件内使用:

  1. <script lang="ts">
  2. import { defineComponent } from "vue";
  3. import useCurrentInstance from "@/utils/useCurrentInstance";
  4. export default defineComponent({
  5. setup() {
  6. const { proxy } = useCurrentInstance();
  7. console.log(proxy);
  8. },
  9. });
  10. </script>

vue3+ts使用getCurrentInstance报错

vue3中没有this + 各种api的方法

vue3提供的方法,创建类似于this的实例。

  1. const instance = getCurrentInstance()
  2. const a1= getCurrentInstance();
  3. a1.$toast({type: 'error', text: '登录失败' });

这种只适合本地调试,运行到线上就会报错,报错详情为:

类型“ComponentInternalInstance | null”上不存在属性“proxy”。ts(2339)

然后下面会报这个错误

Unsafe member access .$axios on an `any` value. eslint@typescript-eslint/no-unsafe-member-access

Unsafe call of an `any` typed value. eslint@typescript-eslint/no-unsafe-call

原因:

getCurrentInstance()的返回类型存在null所以在此处添加断言即可。

在proxy后面添加?来过滤null的结果,即:

  1. const instance = getCurrentInstance()?.proxy
  2. instance ?.$toast('请xxx!')

以上就是Vue3之getCurrentInstance与ts怎么结合使用的详细内容,更多关于Vue3之getCurrentInstance与ts怎么结合使用的资料请关注九品源码其它相关文章!