locale.ts 1.2 KB
Newer Older
Q
qiang 已提交
1
import { useI18n } from '@dcloudio/uni-core'
fxy060608's avatar
fxy060608 已提交
2 3 4 5 6
import { defineOnApi, defineSyncApi } from '../../helpers/api'

const API_SET_LOCALE = 'setLocale'
const API_GET_LOCALE = 'getLocale'
const API_ON_LOCALE_CHANGE = 'onLocaleChange'
Q
qiang 已提交
7

Q
qiang 已提交
8
export const getLocale = defineSyncApi<typeof uni.getLocale>(
fxy060608's avatar
fxy060608 已提交
9
  API_GET_LOCALE,
Q
qiang 已提交
10
  () => {
fxy060608's avatar
fxy060608 已提交
11 12 13 14 15 16
    // 优先使用 $locale
    const app = getApp({ allowDefault: true })
    if (app && app.$vm) {
      return app.$vm.$locale
    }
    return useI18n().getLocale()
Q
qiang 已提交
17 18 19
  }
)

fxy060608's avatar
fxy060608 已提交
20 21
export const onLocaleChange = defineOnApi(API_ON_LOCALE_CHANGE, () => {})

Q
qiang 已提交
22
export const setLocale = defineSyncApi<typeof uni.setLocale>(
fxy060608's avatar
fxy060608 已提交
23
  API_SET_LOCALE,
Q
qiang 已提交
24
  (locale) => {
fxy060608's avatar
fxy060608 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38
    const oldLocale = getApp().$vm.$locale
    if (oldLocale !== locale) {
      getApp().$vm.$locale = locale
      if (__PLATFORM__ === 'app') {
        const pages = getCurrentPages()
        pages.forEach((page) => {
          UniServiceJSBridge.publishHandler(
            API_SET_LOCALE,
            locale,
            page.$page.id
          )
        })
        weex.requireModule('plus').setLanguage(locale)
      }
fxy060608's avatar
fxy060608 已提交
39 40
      // 执行 uni.onLocaleChange
      UniServiceJSBridge.invokeOnCallback(API_ON_LOCALE_CHANGE, { locale })
fxy060608's avatar
fxy060608 已提交
41
      return true
fxy060608's avatar
fxy060608 已提交
42
    }
fxy060608's avatar
fxy060608 已提交
43
    return false
Q
qiang 已提交
44 45
  }
)