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