Vue3 getCurrentInstance与ts结合使用的坑

2,137 阅读1分钟

xxx.vue

<script lang="ts" setup>
import { getCurrentInstance } from 'vue';

// 首先 此处 proxy ts会报
// 类型“ComponentInternalInstance | null”上不存在属性“proxy”。ts(2339)
const { proxy } = getCurrentInstance()

// 然后下面会报这个错误
// 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
proxy.$axios('')

以上就是报错的全部内容,接下来我们解决这个问题

问题解决

第一种方法

  • 第一个报错很好理解 因为 getCurrentInstance()的返回类型存在null所以在此处添加断言即可
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加断言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

2.但是改完后我们发现下面依旧会有报错

// 对象可能为 "null"。ts(2531)
proxy.$axios('')

这个解决起来更简单了,在proxy后面添加?来过滤null的结果

proxy?.$axios('')

第二种方法

import { ComponentInternalInstance, getCurrentInstance } from 'vue';
let instance: ComponentInternalInstance | null = getCurrentInstance();//获取app实例

instance?.proxy?.$axios('')

总结:本质上两种方法是一样的