vue-i18n

2024-06-27 09:34:35 115
vue-i18n 是 Vue.js 的一个国际化 (i18n) 插件,专为 Vue 应用设计,提供多语言支持和翻译功能。该插件可以轻松集成到 Vue 项目中,允许开发者使用简洁的 API 管理和切换应用中的多种语言。

特点

  • 易于集成:与 Vue.js 无缝集成,提供全局和组件级别的翻译支持。
  • 多语言支持:支持多种语言,易于切换和管理不同语言的翻译内容。
  • 动态加载:支持按需加载语言文件,优化应用性能。
  • 插件和扩展:支持多种插件和扩展,增强功能和灵活性。
  • 格式化功能:提供数字、日期和时间的格式化功能,适应不同地区的需求。
  • 支持 SSR:在服务器端渲染 (SSR) 的 Vue 应用中支持国际化。

使用场景

  • 多语言网站:需要支持多种语言的 Vue 项目。
  • 实时翻译:在用户界面中实时翻译动态内容。
  • 企业应用:需要处理大量国际化需求的企业级应用程序。
  • 移动应用:使用 Vue.js 开发的移动应用。

安装方式

npm 安装

npm install vue-i18n

yarn 安装

yarn add vue-i18n

使用示例

初始化 vue-i18n

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

Vue.use(VueI18n);

const messages = {
  en: {
    welcome: 'Welcome to our application'
  },
  fr: {
    welcome: 'Bienvenue dans notre application'
  }
};

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

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

在组件中使用

<template>
  <div>
    <p>{{ $t('welcome') }}</p>
    <button @click="changeLanguage('fr')">Change to French</button>
  </div>
</template>

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

常用 API 介绍

  • VueI18n 构造函数:创建 i18n 实例。
    • new VueI18n(options):初始化 i18n 实例,options 包含 localemessages 等配置。
  • $t(key):获取翻译字符串。
    • key:翻译字符串的键。
  • $i18n.locale:当前语言的代码。
    • this.$i18n.locale = 'fr':切换当前语言。
  • $i18n.setLocaleMessage(locale, messages):设置或更新语言的翻译内容。
    • locale:语言代码。
    • messages:翻译内容对象。
  • $i18n.getLocaleMessage(locale):获取指定语言的翻译内容。
    • locale:语言代码。

高级用法

动态加载翻译文件

可以通过异步加载翻译文件来优化性能,尤其适用于大型应用:

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

Vue.use(VueI18n);

const i18n = new VueI18n({
  locale: 'en',
  messages: {}
});

function loadLanguageAsync(lang) {
  if (!i18n.getLocaleMessage(lang)) {
    return axios.get(`/locales/${lang}.json`).then(response => {
      i18n.setLocaleMessage(lang, response.data);
      i18n.locale = lang;
    });
  }
  i18n.locale = lang;
  return Promise.resolve();
}

export default i18n;

使用日期和数字格式化

vue-i18n 提供了内置的日期和数字格式化功能:

const i18n = new VueI18n({
  locale: 'en',
  messages,
  dateTimeFormats: {
    en: {
      short: {
        year: 'numeric', month: 'short', day: 'numeric'
      }
    },
    fr: {
      short: {
        year: 'numeric', month: 'short', day: 'numeric'
      }
    }
  },
  numberFormats: {
    en: {
      currency: {
        style: 'currency', currency: 'USD'
      }
    },
    fr: {
      currency: {
        style: 'currency', currency: 'EUR'
      }
    }
  }
});

在组件中使用:

<template>
  <div>
    <p>{{ $d(new Date(), 'short') }}</p>
    <p>{{ $n(123456, 'currency') }}</p>
  </div>
</template>

官方资料