Search code examples
routesnuxtjs3nuxt3vue-router4

how can i use named routes and their child routes in nuxt 3?


i have this file structure

pages/
--posts/
----[id].vue
----index.vue
--about.vue
--index.vue

and this navbar

<NuxtLink to="/">home</NuxtLink>
<NuxtLink to="/posts">posts</NuxtLink>
<NuxtLink to="/about">about</NuxtLink>

im trying to take parameter with an input in /posts/index.vue page and go to /posts/:id page. i used this in /posts/index.vue

<script setup>
const id = ref('')
</script>

<template>
  <input type="text" v-model="id"><br>
  <NuxtLink :to="`posts/${id}`">go</NuxtLink>
</template>

its works but not in /posts page, I can only access it directly via the url. (like /posts/3) but I can't redirect with NuxtLink because when i try to go to post page i get 500 Missing required param "id" error. i dont know why, is this route not correct ?

i changed NuxtLink :to property to template literals

<NuxtLink :to="`posts/${id}`">go</NuxtLink>

its work as well, i can access the /posts page and can route to id but this time when I use useActiveClass or useExactActiveClass, (color: green) it is applied to both the /posts link in the navbar and the go link on the posts page.

i dont understand how named routes work. i dont know why first NuxtLink getting error. is this named route not correct ?


Solution

  • Nuxt uses vue-router under the hood, that means posts/index.vue would need its own <NuxtPage> in the template in order to display child pages such as ([id].vue).

    you will have to move your current content in posts/index.vue to another file like latest.vue or blog.vue for example or you can actually display a post above current code that lists posts by putting above your listing loop.