I'm having problems with route params being undefined in components/layouts in Nuxt 3. It seems like a bug but it would be such a critical bug, that I almost don't believe it can be a bug.
Consider the following files:
// pages/index.vue
<template>
<div>
<NuxtLink to="/test-123">Click me</NuxtLink>
</div>
</template>
// pages/test-[id].vue
<script setup lang="ts">
definePageMeta({ layout: "test" });
const route = useRoute();
console.log("page", route.params.id);
</script>
<template>
<div>
{{ route.params.id }}
</div>
</template>
// layouts/test.vue
<script setup lang="ts">
const route = useRoute();
console.log("layout", route.params.id);
</script>
<template>
<div>
<test></test>
<slot></slot>
</div>
</template>
// components/test.vue
<script setup lang="ts">
const route = useRoute();
console.log("component", route.params.id);
</script>
<template>
<div>
{{ route.params.id }}
</div>
</template>
Clicking the link will give the following console output:
layout undefined [test.vue:4:8](http://localhost:3001/_nuxt/layouts/test.vue)
component undefined [test.vue:4:8](http://localhost:3001/_nuxt/components/test.vue)
page 123 [test-[id].vue:6:8](http://localhost:3001/_nuxt/pages/test-[id].vue)
If we navigate from /
to /test-123
with a NuxtLink and print route.params.id
in the layout, component and page, only the page is able to access the id. The layout and component will print undefined. If I reload the page, the component, layout and page all are able to access the route params. So the issue only occurs when navigating from one page to another.
I'm on Nuxt 3.4.2
. Here is a reproduction of the issue.
Is this a bug or am I doing something wrong here?
Just to add a "shortcut" here: ivan119 found a different solution that has been working for me, as seen in his comment on the Github issue OP created: https://github.com/nuxt/nuxt/issues/20471#issuecomment-1785954699
I lost much time until i found solution, please try
const route = useRouter().currentRoute.value const id = route.params.id
for some reason "useRoute().params.id" is cached
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With