From 1f95f3f119d5e1fd2efdd049e15870e4db47fe94 Mon Sep 17 00:00:00 2001 From: Jens Kuerschner Date: Mon, 9 Oct 2023 14:08:10 +0200 Subject: [PATCH] fix locale switcher --- demo/components/languageSwitcher.vue | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/demo/components/languageSwitcher.vue b/demo/components/languageSwitcher.vue index 964dae21..242fe93c 100644 --- a/demo/components/languageSwitcher.vue +++ b/demo/components/languageSwitcher.vue @@ -3,14 +3,28 @@ import { set, LSKey } from '@/utils/localStorage'; import { Listbox, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/vue'; import { LanguageIcon, CheckIcon, ChevronDownIcon } from '@heroicons/vue/20/solid'; -const { locale, locales } = useI18n(); +type LocaleObject = { + code: string; + name: string; +}; + +interface ExtendedI18n extends ReturnType { + locales: ComputedRef; +} + +const { locale, locales } = useI18n() as ExtendedI18n; const switchLocalePath = useSwitchLocalePath(); const currentId = locales.value.findIndex((e: { code: string; }) => e.code === locale.value); -const currentLanguage = ref(locales.value[currentId]); +function getLocaleObject(index: number): LocaleObject | null { + const item = locales.value[index]; + return typeof item === 'object' && 'code' in item ? item : null; +} +const currentLanguage = ref(getLocaleObject(currentId)); // push route when locale change has been detected -watch(currentLanguage, val => { +watch(currentLanguage, (val: LocaleObject|null) => { + if (!val) return; set(LSKey.LANG, val.code); navigateTo(switchLocalePath(val.code)); }); @@ -24,7 +38,7 @@ watch(currentLanguage, val => { - {{ currentLanguage.name }} + {{ currentLanguage?.name }}