refactor: setup
This commit is contained in:
parent
970b6538e2
commit
3079867e2a
7 changed files with 38 additions and 42 deletions
26
plugins/setup-i18n.ts
Normal file
26
plugins/setup-i18n.ts
Normal file
|
@ -0,0 +1,26 @@
|
|||
import { COOKIE_MAX_AGE, STORAGE_KEY_LANG } from '~/constants'
|
||||
|
||||
export default defineNuxtPlugin(async (nuxt) => {
|
||||
const i18n = nuxt.vueApp.config.globalProperties.$i18n
|
||||
const { setLocale, locales } = nuxt.vueApp.config.globalProperties.$i18n
|
||||
const cookieLocale = useCookie(STORAGE_KEY_LANG, { maxAge: COOKIE_MAX_AGE })
|
||||
const isFirstVisit = cookieLocale.value == null
|
||||
|
||||
if (process.client && 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
|
||||
cookieLocale.value = lang || 'en-US'
|
||||
}
|
||||
|
||||
if (cookieLocale.value && cookieLocale.value !== i18n.locale)
|
||||
await setLocale(cookieLocale.value)
|
||||
|
||||
if (process.client) {
|
||||
watchEffect(() => {
|
||||
cookieLocale.value = i18n.locale
|
||||
})
|
||||
}
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue