N
Nuxt5mo ago
ncls.

React to route change in layout

Hello, I have a sidenav in my layout which has URLs depending on the route parameter. So e.g. I have the URL /items/12 and now my sidenav should have links like /items/12/buy, however that only works if I reload since the layout is static. If I now navigate to /item/13, the link will say /items/undefined I tried using a computed like this:
const route = useRoute();
const params= computed(() => route.params);
const route = useRoute();
const params= computed(() => route.params);
But this results in the exact same behavior. What can I do to prevent this?
Solution:
@ncls. ```ts const router = useRouter(); ...
Jump to solution
7 Replies
ncls.
ncls.OP4mo ago
bump bump again
ncls.
ncls.OP4mo ago
I just found out that that's only when I use the code in the setup of the layout. Here's a reproduction example: https://stackblitz.com/edit/nuxt-starter-bnnw74?file=layouts%2Fdefault.vue,pages%2F[...slug].vue
StackBlitz
Layout setup issue - StackBlitz
A Nuxt.js project based on @nuxt/content and nuxt
Solution
Sibyl
Sibyl4mo ago
@ncls.
const router = useRouter();

const x = computed(() => router.currentRoute.value.path);
const router = useRouter();

const x = computed(() => router.currentRoute.value.path);
ncls.
ncls.OP4mo ago
Hi, thanks for your help. However, I forgot to change the code in the question but I actually found out that the issue is just the params which I need. You can see the issue in my reproduction example above.
Sibyl
Sibyl4mo ago
well you can get params still currentRoute.value is the same thing useRoute() returns
ncls.
ncls.OP4mo ago
Let me try real quick
ncls.
ncls.OP4mo ago
So basically I was just an idiot... I made a sidenav that used the route parameters and I defined an array for the different links where I inserted these params but I didn't make that array a computed...

Did you find this page helpful?