vue实现国际化(vue-i18n)

使用vue-i18n插件来实现vue项目中的国际化功能

vue-i18n安装

npm install vue-i18n

全局使用

import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

const messages = {
    'en-US': {
        message: {
            hello: 'hello word'
        }
    },
    'zh-CN': {
        message: {
            hello: '欢迎'
        }
    }
}

const i18n = new VueI18n({
    locale:'zh-CN',
    messages
})

// 创建 Vue 根实例
new Vue({
  i18n,
  ...
}).$mount('#app')

vue页面中使用

<p>{{ $t('message.hello') }}</p>

输出如下

<p>欢迎</p>

可传参数

onst messages = {
  en-US: {
    message: {
      hello: '{msg} world'
    }
  }
}

使用模版:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>

输出如下:

<p>hello world</p>

回退本地化

const messages = {
  en: {
    message: 'hello world'
  },
  ja: {
    // 没有翻译的本地化 `hello`
  }
}

上面语言环境信息的 ja 语言环境中不存在 message 键,当我们使用ja环境中的message时就会出现问题。

此时,我们可以在 VueI18n 构造函数中指定 fallbackLocale为en,message键就会使用 en 语言环境进行本地化。

如下所示:

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

使用如下:

<p>{{ $t('message') }}</p>

输出如下:

<p>hello world</p>

PS: 默认情况下回退到 fallbackLocale 会产生两个控制台警告:

[vue-i18n] Value of key 'message' is not a string!
[vue-i18n] Fall back to translate the keypath 'message' with 'en' locale.

为了避免这些警告 (同时保留那些完全没有翻译给定关键字的警告),需初始化 VueI18n 实例时设置 silentFallbackWarn:true.

如果想要关闭全部由未翻译关键字造成的警告,可以设置silentTranslationWarn: true
如下:

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: 'ja',
  fallbackLocale: 'en',
  messages
})
原文地址:https://www.cnblogs.com/wangyingblock/p/15438016.html