vue项目做i18n国际化详细步骤及代码示例

1,442 阅读2分钟

在 Vue 项目中实现国际化(i18n)通常涉及以下步骤:

步骤 1: 安装依赖

首先,你需要安装 Vue I18n 插件,它是一个 Vue.js 的国际化插件。

npm install vue-i18n

或者,如果你使用的是 Yarn:

yarn add vue-i18n

步骤 2: 创建语言文件

在项目中创建一个 locales 文件夹,并在其中为每种语言创建一个 JSON 文件。例如:

src/
└── locales/
    ├── en.json
    └── zh.json

在每个文件中,定义你的翻译字符串:

// src/locales/en.json
{
  "hello": "Hello",
  "welcome": "Welcome to our application"
}

// src/locales/zh.json
{
  "hello": "你好",
  "welcome": "欢迎来到我们的应用"
}

步骤 3: 配置 Vue I18n

在你的 Vue 项目中,创建一个 i18n.js 文件来配置 Vue I18n:

// src/i18n.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

const messages = {
  en: {
    message: {
      hello: 'Hello',
      welcome: 'Welcome to our application'
    }
  },
  zh: {
    message: {
      hello: '你好',
      welcome: '欢迎来到我们的应用'
    }
  }
};

const i18n = new VueI18n({
  locale: 'en', // 设置默认语言
  messages
});

export default i18n;

步骤 4: 在 Vue 实例中使用 Vue I18n

在你的 Vue 实例中引入并使用 Vue I18n:

// src/main.js
import Vue from 'vue';
import App from './App.vue';
import i18n from './i18n';

new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app');

步骤 5: 在组件中使用翻译

在你的 Vue 组件中,使用 this.$t 方法来访问翻译字符串:

<template>
  <div>
    <h1>{{ $t('message.hello') }}</h1>
    <p>{{ $t('message.welcome') }}</p>
  </div>
</template>

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

步骤 6: 切换语言

你可以创建一个方法来切换语言,并在需要时更新 Vue I18n 实例的 locale 属性:


// src/i18n.js
// ...之前的代码

export function setLocale(lang) {
  i18n.locale = lang;
}

// src/App.vue
<template>
  <div>
    <button @click="setLocale('en')">English</button>
    <button @click="setLocale('zh')">中文</button>
    <p>{{ $t('message.hello') }}</p>
  </div>
</template>

<script>
import { setLocale } from './i18n';

export default {
  name: 'App',
  methods: {
    setLocale
  }
}
</script>

步骤 7: 处理动态内容

如果你需要在翻译字符串中包含动态内容,可以使用占位符:

// src/locales/en.json
{
  "greeting": "Hello, {name}!"
}

在组件中使用:

<template>
  <div>
    <p>{{ $t('greeting', { name: 'Alice' }) }}</p>
  </div>
</template>

步骤 8: 构建和部署

确保你的国际化配置在构建过程中被正确处理。如果你使用的是 Vue CLI,国际化通常会被自动处理。如果你使用的是其他构建工具,确保国际化配置被正确地包含在最终的构建产物中。

以上步骤提供了一个基本的 Vue 项目国际化实现的概览。根据你的具体需求,你可能需要进行一些调整和扩展。例如,你可能需要添加更多的语言支持,或者实现更复杂的国际化功能,如日期和数字格式化、本地化等。