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 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践举例
这篇文章主要介绍了Vue 2 项目中配置 Tailwind CSS 和 Font Awesome 的最佳实践举例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2025-05-05
解决vue3+vite配置unplugin-vue-component找不到Vant组件
这篇文章主要为大家介绍了vue3+vite配置unplugin-vue-component找不到Vant组件问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-09-09
vite5+vue3+ import.meta.glob动态导入vue组件图文教程
import.meta.glob是Vite提供的一个特殊功能,它允许你在模块范围内动态地导入多个模块,这篇文章主要给大家介绍了关于vite5+vue3+ import.meta.glob动态导入vue组件的相关资料,需要的朋友可以参考下2024-07-07


最新评论