Hello! ππΌ I'm back after wayyy too long! Here's my first blog post on something that's actually tech-related. π©π»βπ» This is a quick post on how to create named routes in Nuxt.js.
Table of Contents:
Introduction
In Vue.js, we can create routes with page names so we don't always have to specify a path for an internal route in our application. This handy way of creating routes are called named routes.
However, while working with Nuxt.js in a new project, I wanted to see if I could do the same with Nuxt, since it's based on Vue.js. I was worried I couldn't because Nuxt.js automatically generates Vue routing for us so hypothetically, I thought I wouldn't be able to customize the to
in the <NuxtLink>
component without adding a route name in Router instance. π₯²
But, being curious and tenacious, I tried the same feature in my Nuxt app - and voilΓ ... It works, too!
How to replicate
Is equal to...
I hope this helps someone! In my process, I spent hours trying to find a concrete post on StackOverFlow and Nuxt.js documentation, but there wasn't anything at all too concrete. The only way I found out was through actually applying the idea in code π .
Context
The context for this use-case was for pagination / page queries. I needed a way to pass a query for pagination in the to
portion of the <NuxtLink>
, so hence I defaulted to named routes. I didn't apply the same context in the code photos, but it should work either way (if not, please comment below or message me).
Gist of the story: You don't need to give your route names in Nuxt.js to use named routes.
Anyway, this is it for today! Stay safe and well everyone β€οΈ
Extra: Add to your content creation toolkit
Curious what I used for the beautiful code photos? πΈ
-
Polacode - a VSCode extension
- NOTE: For Polacode to work, you cannot simply highlight code from bottom up as in the demo. You must copy-paste it into the Polacode panel! (An FYI since I thought I would never be able to use it until I used my eyes to read π)
Top comments (3)
You have a file pages/about.vue.
You link to it with to={name: "about" } in 100 places in your code...
At some point we need to changes name of the route to page/AboutPage.vue
Are your old 109 links still working?
How did you define a custom name "page" to the new route pages/AboutPage.vue?
how did you choose the name 'Home' ? why ?
I chose the name βhomeβ rather than the usual β/β path for clarity reasons (easier to know youβre on the homepage when it says βhomeβ!). Hope this helps, let me know if you have any questions.