添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

首先,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('')

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

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

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

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

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

    proxy?.$axios('')
    

    以上,问题解决!