From dbf604cb34a1304add4c8b68db445eaa4db3350a Mon Sep 17 00:00:00 2001 From: NamesMT Date: Sat, 16 Nov 2024 15:08:18 +0000 Subject: [PATCH] feat: add global `$li18n` provide with `renderKey` to reactively render locale changes --- apps/frontend/app/pages/index.vue | 7 +------ apps/frontend/app/plugins/{i18n.ts => li18n.ts} | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 8 deletions(-) rename apps/frontend/app/plugins/{i18n.ts => li18n.ts} (79%) diff --git a/apps/frontend/app/pages/index.vue b/apps/frontend/app/pages/index.vue index bba3700..0757abe 100644 --- a/apps/frontend/app/pages/index.vue +++ b/apps/frontend/app/pages/index.vue @@ -14,11 +14,6 @@ definePageMeta({ }) const { t, locale, setLocale } = useI18n() - -const dayjsRenderKey = ref(0) -// Fast trigger dayjs re-render after locale change -watch(locale, () => setTimeout(() => ++dayjsRenderKey.value, 100)) - const runtimeConfig = useRuntimeConfig() const colorMode = useColorMode() const { $apiClient, $auth } = useNuxtApp() @@ -90,7 +85,7 @@ const { isPending, isError, data, error } = useQuery({ @pointerdown="setLocale(locale === 'en' ? 'vi' : 'en')" /> -
+
{{ dayjs().format('dddd') }}
diff --git a/apps/frontend/app/plugins/i18n.ts b/apps/frontend/app/plugins/li18n.ts similarity index 79% rename from apps/frontend/app/plugins/i18n.ts rename to apps/frontend/app/plugins/li18n.ts index c0fbf16..48abeb4 100644 --- a/apps/frontend/app/plugins/i18n.ts +++ b/apps/frontend/app/plugins/li18n.ts @@ -1,7 +1,7 @@ import { defaultOptions } from 'primevue/config' export default defineNuxtPlugin({ - name: 'local-i18n', + name: 'local-li18n', parallel: true, dependsOn: [ 'local-auth', @@ -15,8 +15,11 @@ export default defineNuxtPlugin({ firstDayOfWeek: 1, } + const li18n = reactive({ + renderKey: 0, + }) + watchImmediate(() => $i18n.locale.value, async (locale) => { - // @ts-expect-error locale might not be defined await setDayjsLocale(locale).catch(() => { console.error(`Failed to set '${locale}' for dayjs hook`) }) switch (locale) { @@ -24,6 +27,14 @@ export default defineNuxtPlugin({ primevue.config.locale = { ...baseLocale } break } + + ++li18n.renderKey }) + + return { + provide: { + li18n, + }, + } }, })