How to Use Routing and Dynamic Routing in Nuxt3
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
An article on how to use routing and dynamic routing in Nuxt3.
Introduction
In Nuxt2, I remember that various directories were automatically set up for dynamic routing, but in Nuxt3, the following directory structure didn’t work as expected.
Dynamic routing allows you to create a route for the /about
page by simply creating directories and files like pages/about/index.vue
, without the need for a routing file.
Solution
Modify app.vue
as Follows
<template>
<NuxtPage />
</template>
<NuxtPage />
is a wrapped component similar to RouterView
in Vue.
<NuxtPage page-key="static" />
<NuxtPage :page-key="route => route.fullPath" />
You can change rendering conditions by setting a key. For more details, see Nuxt - NuxtPage.
Create layouts/default.vue
<template>
<div>
<header>
<li>TOP</li>
<li>ABOUT</li>
<li>CONTACT</li>
</header>
<main>
<!-- The layout for each page will appear in this slot -->
<slot />
</main>
</div>
</template>
Create pages/about/index.vue
<template>
<div>About</div>
</template>
After accessing http://localhost:3000/about
, it displayed successfully.
Note: pages
and layouts
directories are not included by default, so you’ll need to create them manually.
The directory structure is shown in the image below.
When Things Don’t Work
Rebuild After Adding a Page
Stop the local server with the following command:
Control + C
Restart the local server:
yarn dev
Or:
npm run dev
Conclusion
That’s it for this article on implementing dynamic routing in Nuxt3.
I hope this helps someone.