Browse Source

fix: 默认语言修复

liangan 1 week ago
parent
commit
0ecfc43dc3
2 changed files with 20 additions and 2 deletions
  1. 18 1
      src/locale/index.ts
  2. 2 1
      src/pages/mine/setting.vue

+ 18 - 1
src/locale/index.ts

@@ -17,13 +17,30 @@ const supportedLocales = ['en', 'zh-Hans', 'bn'] as const
 type SupportedLocale = typeof supportedLocales[number]
 
 function normalizeLocale(locale: string | undefined | null): SupportedLocale {
+  if (!locale)
+    return 'bn'
   if (supportedLocales.includes(locale as SupportedLocale))
     return locale as SupportedLocale
+
+  const lower = locale.toLowerCase()
+  if (lower.startsWith('en'))
+    return 'en'
+
   return 'bn'
 }
 
+function getInitialLocale(): SupportedLocale {
+  const storedLocale = uni.getStorageSync('app_locale')
+  if (storedLocale)
+    return normalizeLocale(storedLocale)
+
+  const systemLocale = uni.getSystemInfoSync().language || uni.getLocale()
+  const normalized = normalizeLocale(systemLocale)
+  return normalized === 'en' ? 'en' : 'bn'
+}
+
 const i18n = createI18n({
-  locale: normalizeLocale(uni.getLocale()), // 获取已设置的语言,fallback 语言需要再 manifest.config.ts 中设置
+  locale: getInitialLocale(), // 获取已设置的语言,fallback 语言需要再 manifest.config.ts 中设置
   messages,
   allowComposition: true,
 })

+ 2 - 1
src/pages/mine/setting.vue

@@ -31,11 +31,12 @@ function normalizeLocale(locale: string | undefined | null) {
   return 'bn'
 }
 
-const language = ref(normalizeLocale(uni.getLocale()))
+const language = ref(normalizeLocale(uni.getStorageSync('app_locale') || uni.getLocale()))
 function changeLanguage(data: any) {
   console.log(data)
   // 下面2句缺一不可!!!
   uni.setLocale(data.value)
+  uni.setStorageSync('app_locale', data.value)
   i18n.global.locale = data.value
 }
 function logout() {