Vue3 ts setup getCurrentInstance 使用时遇到的问题及解决


环境

vscode
typescript4
vue3

问题描述

首先,vue3中的全局变量及方法的配置较vue2中的变化大家应该已经知道了,不清楚的可以查看官方说明,但是按照官方文档结合typescript使用时遇到了问题:

axios.ts

// axios.ts
import axios from 'axios'
const app = Vue.createApp({})

// 全局自定义属性
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

app.config.globalProperties.$axios = axios

任意.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('')

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

问题解决

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

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

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

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

proxy?.$axios('')

以上,问题解决!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM