醉菜鸟 2022-01-05 09:00:15

VUE:在 vue 3.x 中使用 i18n

如果未使用element-plus 请忽略element

安装

npm i vue-i18n@next
import { createI18n } from 'vue-i18n/index'

import elementEnLocale from 'element-plus/lib/locale/lang/en'
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn'
import { local_set, local_get } from '@utils/helpers'

import enLocale from './en'
import zhLocale from './zh'

const I18nMessages = {
  en: enLocale,
  zh: zhLocale
}

const ElementMessages = {
  en: elementEnLocale,
  zh: elementZhLocale
}

export function getLocale() {
  const Lang = local_get('language')
  if (Lang) return Lang
  // if has not choose language
  const language = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(I18nMessages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return 'zh'
}

export function setLocale(lang) {
  local_set('language', lang)
}

const i18n = createI18n({
  locale: getLocale(),
  messages: I18nMessages,
  silentTranslationWarn: true
})

export default i18n

export const locale = ElementMessages[getLocale()]

入口文件添加

import i18n, { locale } from '/resources/lang'

app.use(ElementPlus, {
  locale: locale
})

app.use(i18n)
意见反馈