vue-i18n使用$t導致的Typescript報錯問題及解決
問題
在 Vue3 項目中使用 vue-i18n v9.14.0 時,可以:
<template>
<div>{{ t('xxx') }}</div>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
</script>
也可以直接使用 $t:
<template>
<div>{{ $t('xxx') }}</div>
</template>
雖然可以正常渲染,但會有 Typescript 的報錯:

解決
因為 vue-i18n 在 Vue 實例上添加了該屬性,比如:
<script setup lang="ts">
// getCurrentInstance 需要在組件中使用。
import { getCurrentInstance } from "vue";
const {
appContext: {
config: { globalProperties },
},
} = getCurrentInstance();
console.log(globalProperties.$t);
</script>
所以根據(jù)報錯信息,猜測是 globalProperties 對象上沒有定義這個屬性,所以報錯。那就看下這個屬性的類型定義:
// node_modules\@vue\runtime-core\dist\runtime-core.d.ts
export declare const getCurrentInstance: () => ComponentInternalInstance | null;
export interface ComponentInternalInstance {
// ...
appContext: AppContext;
}
export interface AppContext {
// ...
config: AppConfig;
}
export interface AppConfig {
// ...
globalProperties: ComponentCustomProperties & Record<string, any>;
}
// 默認為空
export interface ComponentCustomProperties {
}
解決:手動添加類型聲明文件,給 ComponentCustomProperties 添加 $t 屬性即可。
目錄 src/vue-i18n.d.ts,
/* eslint-disable */
import Vue from "vue";
declare module "@vue/runtime-core" {
export interface ComponentCustomProperties {
$t: (key: string, ...args: any[]) => string;
}
}
注意,要保證該聲明文件在 tsconfig.json 配置文件的 include 配置項中。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue中實現(xiàn)點擊按鈕滾動到頁面對應(yīng)位置的方法(使用c3平滑屬性實現(xiàn))
這篇文章主要介紹了vue中實現(xiàn)點擊按鈕滾動到頁面對應(yīng)位置的方法,這段代碼主要使用c3平滑屬性實現(xiàn),需要的朋友可以參考下2019-12-12
VUE跨域問題Access to XMLHttpRequest at
今天發(fā)現(xiàn)一個錯誤,VUE發(fā)送請求的時候不能請求到正確數(shù)據(jù),VUE跨域問題Access to XMLHttpRequest at,本文就詳細的來介紹一下解決方法,感興趣的可以了解一下2022-05-05
解決vue-cli項目打包出現(xiàn)空白頁和路徑錯誤的問題
今天小編就為大家分享一篇解決vue-cli項目打包出現(xiàn)空白頁和路徑錯誤的問題。具有很好的參考價值。希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue前端動態(tài)導入文件之import.meta.glob導入圖片詳細過程
在Vue3中你可以使用import.meta.glob來動態(tài)加載主題文件,并通過TypeScript實現(xiàn)精確的類型推斷,這篇文章主要介紹了vue前端動態(tài)導入文件之import.meta.glob導入圖片的相關(guān)資料,需要的朋友可以參考下2025-07-07

