index.js 2 KB
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import elementEsLocale from 'element-ui/lib/locale/lang/es'// element-ui lang
import elementJaLocale from 'element-ui/lib/locale/lang/ja'// element-ui lang
import enLocale from './en'
import zhLocale from './zh'
import esLocale from './es'
import jaLocale from './ja'

Vue.use(VueI18n)

const messages = {
  en_US: {
    ...enLocale,
    ...elementEnLocale
  },
  zh_CN: {
    ...zhLocale,
    ...elementZhLocale
  },
  es: {
    ...esLocale,
    ...elementEsLocale
  },
  ja: {
    ...jaLocale,
    ...elementJaLocale
  }
}
export function getLanguage() {
  const chooseLanguage = Cookies.get('language')
  if (chooseLanguage) return chooseLanguage

  // if has not choose language
  const language = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return 'zh_CN'
}
const i18n = new VueI18n({
  // set locale
  // options: en | zh | es
  locale: getLanguage() || 'zh_CN',
  // set locale messages
  messages,
  // 控制台不打印警告
  silentTranslationWarn: true
})
// 自动提取脚本只匹配$t,所以给个别名
i18n.$t = i18n.t
/*
window.i18n = i18n
console.log({i18n}) */
/*
用法
$l('title')         => titleZh
$l(item, 'title')   => item.titleZh
$l(null, 'title')   => titleZh
$l()                => Zh
*/
Vue.prototype.$l = i18n.l = (object, field = '') => {
  const prefix = i18n.locale.split('_')[0]
  const append = prefix.charAt(0).toUpperCase() + prefix.toLowerCase().substr(1)
  if (typeof object === 'string') {
    return object + append
  }
  // 如果object是null或者字符串则返回字段名
  if (!object) return field + append

  return object[field + append] || object[field]
}
export default i18n