I’m using Nuxt 3 and I need some advice. I installed the plugin i18n for Nuxt and I using “dynamic routing” on the translation of the URL address.
I would need to evaluate whether my solution is correct:
in my nuxt.config.js I have it set this:
i18n: {
pages: {
login: {
en: '/login'
de: '/anmeldung',
},
'products/[type]': {
en: '/produkty/[type]'
de: '/produkte/[typ]'
},
}
}
for my routing I create composable “composables/useLocaleRouting.js”:
const dynamicRouteLocalParams = {
'products-type': {
myProducts: {
en: 'my-products',
de: 'meine-produkte',
},
allProducts: {
en: 'all-products',
de: 'alle-Produkte',
},
discountProducts: {
en: 'especially-products',
de: 'allem-produkte',
},
},
}
const getDynamicRouteLocalParam = (routePath) => {
return routePath.split('.').reduce((a, b) => a[b], dynamicRouteLocalParams)[currentLocale]
}
const createDynamicLocaleRoute = (routePath) => {
const route = localeRoute({
name: routePath.split('.')[0],
params: { type: getDynamicRouteLocalParam(routePath) }
})
return route.fullPath
}
const isDynamicLocaleRoute = (routePath) => {
return router.currentRoute.value.params?.type === getDynamicRouteLocalParam(routePath)
}
return {
createDynamicLocaleRoute,
isDynamicLocaleRoute,
}
And using this composable is:
<template>
<div>
<NuxtLink
class="navigation-item"
:class="{ 'selected': isDynamicLocaleRoute(createPath(item)) }"
v-for="item in menuItems" :key="item.type"
:to="createDynamicLocaleRoute(createPath(item))"
>
{{ horizontalNavigationLabel(createPath(item)) }}
</NuxtLink>
</div>
</template>
<script setup>
const { createDynamicLocaleRoute, isDynamicLocaleRoute } = useLocaleRouting()
const t = useI18n()
const menuItems = [
{ routeName: 'products-type', type: 'myProducts' },
{ routeName: 'products-type', type: 'pricingProducts' },
{ routeName: 'products-type', type: 'allProducts' },
{ routeName: 'products-type', type: 'discountProducts' },
]
const horizontalNavigationLabel = computed(() => {
return path => t.t(`horizontalNavigation.${path}`)
})
const createPath = computed(() => {
return item => `${item.routeName}.${item.type}`
})
</script>
In principle, the getDynamicRouteLocalParam function finds the translation parameter for redirection according to the selected locale, and the createDynamicLocaleRoute function creates a routing path using localeRoute
This is an example of my code, please see if this is a suitable solution or if you have a better solution. well thank you