Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route params are undefined in layouts/components in Nuxt 3

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?

like image 788
Joachim Avatar asked Sep 16 '25 22:09

Joachim


1 Answers

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

like image 150
Stretsh Avatar answered Sep 18 '25 18:09

Stretsh