useI18n.ts 1.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { getEnvLocale } from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
2
import { BuiltInLocale, initVueI18n } from '@dcloudio/uni-i18n'
fxy060608's avatar
fxy060608 已提交
3

fxy060608's avatar
fxy060608 已提交
4
let i18n: ReturnType<typeof initVueI18n>
fxy060608's avatar
fxy060608 已提交
5

Q
qiang 已提交
6 7 8 9
interface webviewStyleWithLanguage extends PlusWebviewWebviewStyles {
  language: string
}

fxy060608's avatar
fxy060608 已提交
10
export function useI18n() {
fxy060608's avatar
fxy060608 已提交
11 12 13
  if (!i18n) {
    let language: BuiltInLocale
    if (__PLATFORM__ === 'h5') {
fxy060608's avatar
fxy060608 已提交
14 15 16
      if (__NODE_JS__) {
        language = getEnvLocale() as BuiltInLocale
      } else {
Q
qiang 已提交
17
        language = (__uniConfig.language || navigator.language) as BuiltInLocale
fxy060608's avatar
fxy060608 已提交
18
      }
fxy060608's avatar
fxy060608 已提交
19
    } else if (__PLATFORM__ === 'app') {
Q
qiang 已提交
20 21 22 23 24 25 26
      if (typeof getApp === 'function') {
        language = weex.requireModule('plus').getLanguage() as BuiltInLocale
      } else {
        language = (
          plus.webview.currentWebview().getStyle() as webviewStyleWithLanguage
        ).language as BuiltInLocale
      }
fxy060608's avatar
fxy060608 已提交
27 28 29
    } else {
      language = uni.getSystemInfoSync().language as BuiltInLocale
    }
Q
qiang 已提交
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
    const SET_LOCALE_API = 'i18n.setLocale'
    if (__PLATFORM__ === 'app') {
      i18n = initVueI18n(
        language,
        undefined,
        undefined,
        typeof getApp === 'function'
          ? (locale) => {
              const pages = getCurrentPages()
              pages.forEach((page) => {
                UniServiceJSBridge.publishHandler(
                  SET_LOCALE_API,
                  locale,
                  page.$page.id
                )
              })
              weex.requireModule('plus').setLanguage(locale)
            }
          : undefined
      )
    } else {
      i18n = initVueI18n(language)
    }
    if (__PLATFORM__ === 'app' && typeof getApp !== 'function') {
      UniViewJSBridge.subscribe(SET_LOCALE_API, i18n.setLocale)
    }
fxy060608's avatar
fxy060608 已提交
56
  }
fxy060608's avatar
fxy060608 已提交
57 58
  return i18n
}