index.js 1.4 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
import i18n from '@dcloudio/uni-i18n'

import en from './en.json'
import es from './es.json'
import fr from './fr.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'

const messages = {
  en,
  es,
  fr,
  'zh-Hans': zhHans,
  'zh-Hant': zhHant
}

const fallbackLocale = 'en'

export function initI18n (locale, onChange) {
  i18n.init({
    locale,
    fallbackLocale,
    messages
  })
  if (onChange) {
    i18n.watchLocale((newLocale, oldLocale) => {
      onChange(newLocale, oldLocale)
    })
  }
}

function initLocaleWatcher (app) {
  app.$i18n.vm.$watch('locale', (newLocale) => {
    i18n.setLocale(newLocale)
  }, {
    immediate: true
  })
}

export function t (key, values) {
  if (__VIEW__) {
    return i18n.t(key, values)
  }
  const app = getApp()
  if (!app.$t) {
    /* eslint-disable no-func-assign */
    t = function (key, values) {
      return i18n.t(key, values)
    }
  } else {
    initLocaleWatcher(app)
    /* eslint-disable no-func-assign */
    t = function (key, values) {
      const $i18n = app.$i18n
      const silentTranslationWarn = $i18n.silentTranslationWarn
      $i18n.silentTranslationWarn = true
      const msg = app.$t(key, values)
      $i18n.silentTranslationWarn = silentTranslationWarn
      if (msg !== key) {
        return msg
      }
      return i18n.t(key, values)
    }
  }
  return t(key, values)
}