白屏、闪回与半中半英 用户在语言菜单连点了两次:先点了 English,马上改主意点回中文。300ms 后界面先切成英文,又"闪回"中文;或者更糟——导航是英文、表格列头是中文,半中半英。弱网下切换还会白屏转圈半天,失败后界面停在一种说不清的状态。根因不复杂:语言包是异步 chunk,“切换语言"是一次异步状态迁移,但代码把它写成了一个同步赋值。
竞态的根子:谁后返回谁生效,而不是谁后点击谁生效 // 经典错误写法 async function changeLocale(locale: string) { const messages = await loadMessages(locale) // 网络往返,耗时不可控 i18n.global.setLocaleMessage(locale, messages) i18n.global.locale.value = locale } 连点两次,zh 到 en 的包走得慢、en 到 zh 的包走得快:zh 先激活、en 后激活,最终界面是英文,而用户最后点的是中文。这不是 vue-i18n 的 bug,是我们没做"最后一次意图优先”。完整的解法是一个带版本号守卫的小状态机:
// composables/useLocaleSwitch.ts import { shallowRef } from 'vue' import { i18n } from '@/i18n' import { localeLoaders, DEFAULT_LOCALE, type Locale } from '@/i18n/loaders' const current = shallowRef<Locale>(DEFAULT_LOCALE) const target = shallowRef<Locale>(DEFAULT_LOCALE) // 最近一次请求的语言,重试用 const loading = shallowRef(false) const error = shallowRef<Error | null>(null) const messageCache = new Map<Locale, Record<string, unknown>>() const inflight = new Map<Locale, Promise<Record<string, unknown>>>() let seq = 0 // 切换版本号:过期结果一律丢弃 async function loadMessages(locale: Locale) { const cached = messageCache.get(locale) if (cached) return cached let p = inflight.get(locale) if (!p) { p = localeLoaders[locale]().then((m) => m.default) inflight.set(locale, p) // 并发请求同一语言只下载一次 } try { const messages = await p messageCache.set(locale, messages) return messages } finally { inflight.delete(locale) // 失败不缓存,重试才有意义 } } async function switchLocale(locale: Locale) { const id = ++seq target.value = locale error.value = null loading.value = true try { const messages = await loadMessages(locale) if (id !== seq) return // 已不是最后一次点击,丢弃结果 i18n.global.setLocaleMessage(locale, messages) i18n.global.locale.value = locale // 与上一行同 tick:一次渲染完成切换 current.value = locale document.documentElement.lang = locale } catch (e) { if (id !== seq) return error.value = e instanceof Error ? e : new Error(String(e)) } finally { if (id === seq) loading.value = false // 旧请求不能提前关掉新请求的 loading } } // 语言菜单 hover 时预取,点下去基本命中缓存 function preload(locale: Locale) { void loadMessages(locale).catch(() => {}) } export function useLocaleSwitch() { return { current, target, loading, error, switchLocale, preload } } 几个细节:seq 守卫拦掉所有过期激活,catch 分支同样先看 id——失败也只对"最后一次点击"负责,界面停留在当前语言,绝不半新半旧;loading 的清空带 id 守卫,避免旧请求把新请求的加载态提前结束;inflight 去重解决"连点同一语言下载三次";messageCache 让第二次切换零网络。切换入口的文案用静态映射(别在模板里 new Intl.DisplayNames),失败重试直接复用 target:
...