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

Vue.js 2实现单视图对应独立翻译文件的方法

实现Vue.js 2按语言目录存放组件翻译文件的方案

1. 调整目录结构

首先重构你的翻译文件存储结构,按语言分类目录,每个组件对应同名JSON文件,同时保留公共翻译目录:

src/
├── locales/
│   ├── en/                # 英文翻译目录
│   │   ├── Home.json      # 对应Home.vue的英文翻译
│   │   ├── About.json     # 对应About.vue的英文翻译
│   │   └── common.json    # 公共英文翻译(如按钮、导航)
│   └── fr/                # 法文翻译目录
│       ├── Home.json
│       ├── About.json
│       └── common.json
├── views/
│   ├── Home.vue
│   └── About.vue
└── i18n.js

2. 迁移翻译内容

将原Vue文件中<i18n>代码块的内容拆分到对应语言目录的JSON文件中:

  • 原Home.vue的<i18n>代码块:
    <i18n>
    {
      "en": {
        "title": "Welcome to Home",
        "desc": "This is our home page"
      },
      "fr": {
        "title": "Bienvenue à la page d'accueil",
        "desc": "Ceci est notre page d'accueil"
      }
    }
    </i18n>
    
  • 迁移后locales/en/Home.json:
    {
      "title": "Welcome to Home",
      "desc": "This is our home page"
    }
    
  • 迁移后locales/fr/Home.json:
    {
      "title": "Bienvenue à la page d'accueil",
      "desc": "Ceci est notre page d'accueil"
    }
    

3. 修改i18n.js配置

使用Webpack的require.context批量加载所有翻译文件,合并公共与组件翻译内容(适配Vue-i18n@8.x,对应Vue.js 2):

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

// 定义支持的语言列表
const supportedLangs = ['en', 'fr']
const messages = {}

supportedLangs.forEach(lang => {
  // 加载当前语言下的所有组件翻译文件
  const componentTranslations = require.context(`./locales/${lang}`, false, /\.json$/)
  const componentMessages = componentTranslations.keys().reduce((acc, key) => {
    // 提取文件名(去掉后缀)作为翻译key的前缀
    const fileName = key.replace(/^\.\/(.*)\.\w+$/, '$1')
    acc[fileName] = componentTranslations(key)
    return acc
  }, {})

  // 加载公共翻译文件
  const commonMessages = require(`./locales/${lang}/common.json`)

  // 合并公共与组件翻译
  messages[lang] = {
    ...commonMessages,
    ...componentMessages
  }
})

// 初始化i18n实例
const i18n = new VueI18n({
  locale: 'en', // 默认语言
  fallbackLocale: 'en', //  fallback语言
  messages
})

export default i18n

4. 组件中使用翻译

在Vue组件中通过$t方法访问翻译,格式为[文件名].[翻译key]:

<template>
  <div class="home">
    <h1>{{ $t('Home.title') }}</h1>
    <p>{{ $t('Home.desc') }}</p>
    <button>{{ $t('common.submit') }}</button> <!-- 公共翻译 -->
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>

5. (可选)处理嵌套组件目录

如果你的组件存放在嵌套目录(如views/User/Profile.vue),可修改require.context的参数支持递归加载,并将路径转为层级key:

// 调整组件翻译加载逻辑
const componentTranslations = require.context(`./locales/${lang}`, true, /\.json$/)
const componentMessages = componentTranslations.keys().reduce((acc, key) => {
  // 将路径转为层级key(如User/Profile → User.Profile)
  const keyPath = key.replace(/^\.\/(.*)\.\w+$/, '$1').replace(/\//g, '.')
  acc[keyPath] = componentTranslations(key)
  return acc
}, {})

使用时对应为$t('User.Profile.title')。

6. 语言切换功能

添加切换按钮快速验证翻译效果:

<template>
  <div>
    <button @click="switchLang('en')">English</button>
    <button @click="switchLang('fr')">Français</button>
  </div>
</template>

<script>
export default {
  methods: {
    switchLang(lang) {
      this.$i18n.locale = lang
    }
  }
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:26:13