feat(i18n): 创建 vue-i18n 实例与语言检测/切换核心模块
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import zhCN from './zh-CN'
|
||||
import zhTW from './zh-TW'
|
||||
import en from './en'
|
||||
import ja from './ja'
|
||||
import ko from './ko'
|
||||
import de from './de'
|
||||
import fr from './fr'
|
||||
import es from './es'
|
||||
import pt from './pt'
|
||||
|
||||
export const SUPPORTED_LOCALES = [
|
||||
'zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'de', 'fr', 'es', 'pt',
|
||||
] as const
|
||||
|
||||
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number]
|
||||
|
||||
export const localeNames: Record<SupportedLocale, string> = {
|
||||
'zh-CN': '简体中文',
|
||||
'zh-TW': '繁體中文',
|
||||
'en': 'English',
|
||||
'ja': '日本語',
|
||||
'ko': '한국어',
|
||||
'de': 'Deutsch',
|
||||
'fr': 'Français',
|
||||
'es': 'Español',
|
||||
'pt': 'Português',
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'preferred-locale'
|
||||
|
||||
function detectLocale(): SupportedLocale {
|
||||
const stored = uni.getStorageSync(STORAGE_KEY)
|
||||
if (stored && SUPPORTED_LOCALES.includes(stored)) {
|
||||
return stored as SupportedLocale
|
||||
}
|
||||
|
||||
try {
|
||||
const systemInfo = uni.getSystemInfoSync()
|
||||
const lang = systemInfo.language || ''
|
||||
const normalized = lang.replace(/_/g, '-').toLowerCase()
|
||||
|
||||
for (const locale of SUPPORTED_LOCALES) {
|
||||
if (normalized.startsWith(locale.toLowerCase())) {
|
||||
return locale
|
||||
}
|
||||
}
|
||||
|
||||
if (normalized.startsWith('zh')) {
|
||||
if (normalized.includes('tw') || normalized.includes('hant')) {
|
||||
return 'zh-TW'
|
||||
}
|
||||
return 'zh-CN'
|
||||
}
|
||||
} catch {
|
||||
// getSystemInfoSync may fail in some environments
|
||||
}
|
||||
|
||||
return 'zh-CN'
|
||||
}
|
||||
|
||||
export function setLocale(locale: SupportedLocale): void {
|
||||
if (!SUPPORTED_LOCALES.includes(locale)) return
|
||||
uni.setStorageSync(STORAGE_KEY, locale)
|
||||
i18n.global.locale.value = locale
|
||||
}
|
||||
|
||||
export function getLocale(): SupportedLocale {
|
||||
return i18n.global.locale.value as SupportedLocale
|
||||
}
|
||||
|
||||
export const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: detectLocale(),
|
||||
fallbackLocale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': zhCN,
|
||||
'zh-TW': zhTW,
|
||||
'en': en,
|
||||
'ja': ja,
|
||||
'ko': ko,
|
||||
'de': de,
|
||||
'fr': fr,
|
||||
'es': es,
|
||||
'pt': pt,
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user