Vue 使用I18n

in 前端 with 0 comment

Vue 使用I18n

install

yarn add vue-i18n

./plugins/i18n.js

import { getLanguage, getLanguagesLocale } from './languages'
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const language = getLanguage()
const messages = {}
const locales = getLanguagesLocale()
if (locales) {
  messages[language] = locales
}

// 4、构造一个VueI18n实例
const i18n = new VueI18n({
  locale: language,
  messages
})

// 6、在上面的main.js文件中把i18n挂载到了根实例上。
export default i18n

./languages.js

import { getLanguages } from '@/apis/common'
import i18n from '@/plugins/i18n'
import enUS from 'vant/es/locale/lang/en-US'
import zhCN from 'vant/es/locale/lang/zh-CN'
import { isDevelopment } from '@/utils/helper'

export const VantLocales = {
  'zh-CN': zhCN,
  'en-US': enUS
}

const defaultLanguage = 'zh-CN'

export function getVersion () {
  return isDevelopment()
      ? new Date().getTime()
      : '0100'
}

export const DayjsLocales = {
  'zh-CN': 'zh',
  'en-US': 'en'
}

export function getBrowserLanguage () {
  const browserLanguage = navigator.language || navigator.userLanguage
  if (!browserLanguage) {
    return defaultLanguage
  }
  if (browserLanguage.indexOf('zh') !== -1) {
    return 'zh-CN'
  }

  if (browserLanguage.indexOf('en') !== -1) {
    return 'en-US'
  }

  return defaultLanguage
}

export function getLanguage () {
  let language = localStorage.getItem('accept_language')
  language = language || getBrowserLanguage()
  localStorage.setItem('accept_language', language)
  return language
}

export function getLanguageLocaleKey () {
  const key = getLanguage()
  return `${getVersion()}:${key}:LANGUAGES`
}

export function getLanguagesLocale () {
  const key = getLanguageLocaleKey()
  const locales = localStorage.getItem(key)
  if (locales) {
    return JSON.parse(locales)
  }
  return false
}

export function setLanguagesLocale (data) {
  const key = getLanguageLocaleKey()
  localStorage.setItem(key, JSON.stringify(data))
}

export async function loadLocales () {
  const lang = getLanguage()
  const keys = Object.keys(i18n.getLocaleMessage(lang))
  if (keys.length > 0) {
    return
  }
  const data = await getLanguages(lang, getVersion())
  i18n.setLocaleMessage(lang, data)
  if(!isDevelopment()) {
    setLanguagesLocale(data)
  }
}

使用 main.js

import i18n from './plugins/i18n'
...
new Vue({
  router,
  i18n,
  render: h => h(App)
}).$mount('#app')

如为加载的远程i18n, 则可以在 App.vue created 方法中 加入

// 动态加载语言包
loadLocales()

代码中如何使用?

{{ $t("message") }}<templete/>