vue-i18n使用$t导致的Typescript报错问题及解决
作者:下雪天的夏风
在Vue3项目中使用vue-i18n v9.14.0时,$t属性可能因类型未声明导致TS报错,解决方案是创建src/vue-i18n.d.ts文件,添加至tsconfig.json的include项中,声明$t属性类型
问题
在 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
配置项中。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。