From 38fc2a2faeaf7fb1f91e8915138830d067e40034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E7=BF=94?= Date: Wed, 29 Apr 2026 18:22:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(i18n):=20=E5=88=9B=E5=BB=BA=20vue-i18n=20?= =?UTF-8?q?=E5=AE=9E=E4=BE=8B=E4=B8=8E=E8=AF=AD=E8=A8=80=E6=A3=80=E6=B5=8B?= =?UTF-8?q?/=E5=88=87=E6=8D=A2=E6=A0=B8=E5=BF=83=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/locales/index.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 everything-is-suitable-uniapp/src/locales/index.ts diff --git a/everything-is-suitable-uniapp/src/locales/index.ts b/everything-is-suitable-uniapp/src/locales/index.ts new file mode 100644 index 0000000..6e89809 --- /dev/null +++ b/everything-is-suitable-uniapp/src/locales/index.ts @@ -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 = { + '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, + }, +})