UNPKG

@ithinkdt/core

Version:

iThinkDT Core

49 lines (44 loc) 1.46 kB
import { watch } from 'vue' import { createI18n, lang as _lang, useI18n } from '@ithinkdt/common' import { parseData, saveData, STORE_PREFIX } from '../store' import { lang as langInterceptor } from './lang.interceptor' let i18n function initI18n(options) { const { global, install } = createI18n({ locale: options.defaultLocale, messages: options.globalMessage, }) i18n = global const lang = typeof options.http === 'object' ? langInterceptor({ ...options.http, locale: global.locale, }) : undefined const key = `${STORE_PREFIX}core:i18n` const version = 1 const parse = () => { const data = parseData('local', key, version, (locale) => locale && Object.values(_lang).includes(locale)) if (data) global.locale.value = data } parse() watch( global.locale, (locale, from) => { if (from === locale) return document.querySelector('html').setAttribute('lang', locale) console.debug(`[i18n] locale changed ${from || '[undefined]'} -> ${locale}.`) saveData('local', key, locale === options.defaultLocale ? undefined : locale, version) }, { immediate: true }, ) return { global, lang, install(app) { app.use(install) }, } } export { useI18n, i18n, initI18n, _lang as lang }