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>
所以根据报错信息,猜测是 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 配置项中。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue中实现点击按钮滚动到页面对应位置的方法(使用c3平滑属性实现)
这篇文章主要介绍了vue中实现点击按钮滚动到页面对应位置的方法,这段代码主要使用c3平滑属性实现,需要的朋友可以参考下2019-12-12
VUE跨域问题Access to XMLHttpRequest at
今天发现一个错误,VUE发送请求的时候不能请求到正确数据,VUE跨域问题Access to XMLHttpRequest at,本文就详细的来介绍一下解决方法,感兴趣的可以了解一下2022-05-05
vue前端动态导入文件之import.meta.glob导入图片详细过程
在Vue3中你可以使用import.meta.glob来动态加载主题文件,并通过TypeScript实现精确的类型推断,这篇文章主要介绍了vue前端动态导入文件之import.meta.glob导入图片的相关资料,需要的朋友可以参考下2025-07-07


最新评论