環境
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('')
以上就是報錯的全部內容,接下來我們解決這個問題
問題解決
- 第一個報錯很好理解 因為
getCurrentInstance()
的返回類型存在null
所以在此處添加斷言即可
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加斷言
const { proxy } = getCurrentInstance() as ComponentInternalInstance
2.但是改完后我們發現下面依舊會有報錯
// 對象可能為 "null"。ts(2531)
proxy.$axios('')
這個解決起來更簡單了,在proxy
后面添加?
來過濾null
的結果
proxy?.$axios('')
以上,問題解決!