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

如何在setup函数外及TypeScript文件中使用Vue I18n实例?

在TypeScript文件中正确使用Vue I18n的方法

你的问题出在测试代码里的t函数是自己定义的空实现,完全没关联到Vue I18n的实例,所以只会返回键名而不翻译。按以下步骤修改即可:

1. 修改i18n.ts,导出I18n实例

在你的i18n.ts文件中,需要把创建好的i18n实例导出,这样其他文件才能引用它:

import { createI18n } from 'vue-i18n'
// 确保messages已正确导入,比如import messages from './locales/index'

// 先创建并导出i18n实例
export const i18n = createI18n({
  legacy: false,
  locale: "de",
  fallbackLocale: "de",
  messages,
  missingWarn: false,
  fallbackWarn: false,
  globalInjection: true,
  datetimeFormats: {
    de: {
      date: {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      },
      dateTime: {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      },
    },
  },
})

export const install = (app: any) => {
  app.use(i18n)

  const vuetify = createVuetify({
    components,
    directives,
    theme,
  })

  app.use(vuetify)
}

2. 在目标TS文件中使用实例的t方法

在需要翻译的.ts文件里,导入刚才导出的i18n实例,从i18n.global中解构出t函数(因为你启用了legacy: false,属于Composition API模式):

// 替换为你的i18n.ts实际路径
import { i18n } from '@/plugins/i18n'

const { t } = i18n.global

const col = {
  label: t("location.remark"),
}

额外注意事项

  • 确保你的messages对象中包含de语言下的location.remark键值对,示例:
    // locales/de.ts
    export default {
      location: {
        remark: "Standortbemerkung"
      }
    }
    
  • 如果是在组件的setup函数内使用,更推荐用useI18n钩子:
    import { useI18n } from 'vue-i18n'
    
    setup() {
      const { t } = useI18n()
      const col = { label: t("location.remark") }
      return { col }
    }
    

内容的提问来源于stack exchange,提问作者Mr. A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:35:06