Simplicity is a double-edged sword, most of the time I enjoy what simplicity gave to me, but other times it annoys me, I want to have more control over my product and do things like God.
Over the past year, I spent most of my time working on Vue and especially with Nuxtjs. Nuxtjs is a great framework to create a universal Vue application. It is very simple to build a website with Nuxt. But, like everything else simplicity has cost. Within the last year, we use Nuxt to develop our new website and everything seems perfect. But something lacks.
Our legacy website has two pages, /hotel/HOTEL_SLUG
and /hostel/HOSTEL_SLUG
. These two pages have the same structure but different content, Using Nuxt we have to create two separate page file to create these web pages. But there are tens of pages like this and creating multiple pages is not an option.
What we need is multiple aliases to a single page, but supporting the full functionality of vue-router
isn’t what Nuxt build for. Nuxt tries to keep everything simple to use, this cause to omit some capabilities of vue-router
. Take a look at vue-router
Docs.
Nuxt.js automatically generates the
vue-router
configuration based on your file tree of Vue files inside the pages directory.
We can’t create a single page for each of URLs, on the other hand creating multiple files for pages that do the same work and have the same functionality was annoying. All do we need is creating an alias to a page with different data. This simple problem leads us to build Router Extras Module.
Router extras reveal hidden capabilities of vue-router
with simple JSON/YAML config. With router extras manipulate Nuxt router config. Router extras can:
- Change page path (regardless of its directory structure)
- Pass custom props to page components
- Add meta fields to a route
- Create one or multiple aliases for a page
- Pass custom props to page aliases per alias
- Write
beforeEnter
route guard for a single page
Usage
- Install
@nuxtjs/router-extras
with your favorite package manager
yarn add @nuxtjs/router-extras
# or
npm i @nuxtjs/router-extras
- Register module in nuxt.config.js
{
modules: [
'@nuxtjs/router-extras'
]
}
- Create
<router>
block in page and define routes
<router>
{
path: "/hotel/:slug",
props: {
placeType: "hotel"
},
alias: [
{
path: "/hostel/:slug",
props: [
{
placeType: "hostel"
}
]
}
]
}
</router>
Or if you want to do it in YAML
<router lang="yaml">
path: /hotel/:slug
props:
placeType: hotel
alias:
-
path: /hostel/:slug
props:
placeType: hostel
</router>
<router>
is not a predefined tag in Vue files, so if you want syntax highlighting look at module docs.
Top comments (1)
Thank you for this nice article.