You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中如何在TypeScript文件中使用vue-i18n?

解决方案:Vue3中i18n.global.t报"Cannot read properties of undefined"错误

可能原因及对应解决步骤

1. 确认i18n实例正确初始化并挂载到Vue应用

首先检查你的i18n.ts配置是否正确导出实例,且在main.ts中完成挂载:

// i18n.ts
import { createI18n } from 'vue-i18n'
// 导入你的语言包文件
import en from './locales/en.json'
import zh from './locales/zh.json'

// 创建并导出i18n实例
const i18n = createI18n({
  locale: 'zh', // 默认语言
  fallbackLocale: 'en', // 降级语言
  messages: {
    en,
    zh
  }
})

export default i18n

在main.ts中挂载到Vue应用:

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './i18n'

const app = createApp(App)
app.use(i18n) // 必须先挂载i18n实例
app.mount('#app')

2. 避免在应用挂载前访问i18n.global

i18n.global只有在app.use(i18n)执行后才会被Vue初始化,如果你的index.ts逻辑在应用挂载前运行,就会触发该错误。

解决方法:

  • 将需要使用i18n的逻辑延迟到应用挂载后执行:
// index.ts
import i18n from './i18n'

export function getTranslatedTitle() {
  return i18n.global.t('universitet_title')
}

在main.ts中挂载后调用:

// main.ts
import { getTranslatedTitle } from './index'

app.mount('#app')
// 此时i18n.global已完成初始化
console.log(getTranslatedTitle())

3. 检查i18n实例的导入是否正确

确保index.ts中导入的是你在i18n.ts中导出的已初始化实例,而非重新创建未挂载的实例。错误示例:

// 错误:直接创建新实例但未挂载到Vue应用
import { createI18n } from 'vue-i18n'
const i18n = createI18n({ /* 配置内容 */ })
// 此时i18n.global未被Vue初始化,调用t会报错

4. 组件内使用组合式API替代(若场景允许)

如果是在Vue组件中使用国际化,推荐用useI18n组合式API,而非直接访问i18n.global:

<template>
  <h1>{{ t('universitet_title') }}</h1>
</template>

<script setup>
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
</script>

内容的提问来源于stack exchange,提问作者Bekzod Buranov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 01:41:10