feat(i18n): use preferred language when users first visit (#263)

zio/stable
Alex 2022-12-02 10:17:41 +08:00 committed by GitHub
parent 75d1a39017
commit 0f7de38c24
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 3 deletions

View File

@ -24,11 +24,19 @@ export function setupPageHeader() {
} }
export async function setupI18n() { export async function setupI18n() {
// TODO: guess user language const { locale, setLocale, locales } = useI18n()
const isFirstVisit = !window.localStorage.getItem(STORAGE_KEY_LANG)
const { locale, setLocale } = useI18n()
const localeStorage = useLocalStorage(STORAGE_KEY_LANG, locale.value) const localeStorage = useLocalStorage(STORAGE_KEY_LANG, locale.value)
if (isFirstVisit) {
const userLang = (navigator.language || 'en-US').toLowerCase()
// cause vue-i18n not explicit export LocaleObject type
const supportLocales = unref(locales) as { code: string }[]
const lang = supportLocales.find(locale => userLang.startsWith(locale.code.toLowerCase()))?.code
|| supportLocales.find(locale => userLang.startsWith(locale.code.split('-')[0]))?.code
localeStorage.value = lang || 'en-US'
}
if (localeStorage.value !== locale.value) if (localeStorage.value !== locale.value)
await setLocale(localeStorage.value) await setLocale(localeStorage.value)