From 63470f279c2505154b1cde322bcf11e004fed389 Mon Sep 17 00:00:00 2001 From: DEV_DSW <562304744@qq.com> Date: Tue, 2 Jun 2026 15:02:09 +0800 Subject: [PATCH] refactor(i18n): simplify locale resolution and clean up code Simplify the locale resolution logic in the request utility by directly using stored locale with default fallback, remove the unused getNavigatorLanguages function, and streamline the initial locale setup in the i18n entrypoint while persisting the default locale when no stored locale is present. --- src/i18n/index.ts | 25 ++++++------------------- src/utils/request.ts | 9 +++------ 2 files changed, 9 insertions(+), 25 deletions(-) diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 9d18ad7..585a459 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -1,25 +1,11 @@ import { createI18n } from "vue-i18n"; -import { isSupportedLocale, resolveInitialLocale } from "./locales.ts"; +import { isSupportedLocale } from "./locales.ts"; import { messages } from "./messages.ts"; import { readStoredLocale, writeStoredLocale } from "./storage.ts"; import { defaultLocale } from "./types.ts"; import type { SupportedLocale } from "./types.ts"; import { syncVantLocale } from "./vant.ts"; -function getNavigatorLanguages(): string[] { - if (typeof navigator === "undefined") { - return []; - } - - const languages = navigator.languages ? [...navigator.languages] : []; - - if (languages.length > 0) { - return languages; - } - - return navigator.language ? [navigator.language] : []; -} - function setDocumentLanguage(locale: SupportedLocale): void { if (typeof document === "undefined") { return; @@ -28,10 +14,11 @@ function setDocumentLanguage(locale: SupportedLocale): void { document.documentElement.lang = locale; } -const initialLocale = resolveInitialLocale({ - storedLocale: readStoredLocale(), - navigatorLanguages: getNavigatorLanguages(), -}); +const storedLocale = readStoredLocale(); +const initialLocale = storedLocale ?? defaultLocale; +if (!storedLocale) { + writeStoredLocale(defaultLocale); +} syncVantLocale(initialLocale); setDocumentLanguage(initialLocale); diff --git a/src/utils/request.ts b/src/utils/request.ts index fc1ade8..1751894 100644 --- a/src/utils/request.ts +++ b/src/utils/request.ts @@ -1,6 +1,7 @@ import axios from "axios"; import type { AxiosError, AxiosRequestConfig } from "axios"; -import { getCurrentLocale } from "@/i18n"; +import { readStoredLocale } from "@/i18n/storage"; +import { defaultLocale } from "@/i18n/types"; import type { ApiResponse, NormalizedError, @@ -89,11 +90,7 @@ function resolveRequestLanguage(): string | null { if (context.language) { return context.language; } - try { - return getCurrentLocale(); - } catch { - return null; - } + return readStoredLocale() ?? defaultLocale; } function buildContextHeaders(options?: RequestOptions): Record {