Nuxt enables automatic routing. All you need to do is -
- Create the Nuxt app
- Create Vue pages under
pages
root directory
All pages will automatically be routes in the app - no need for a distinct Vue router definition.
Automatic Routes in Nuxt
Consider the below pages in an example app https://my-app.com-
- Create
/pages/index.vue
for your home page => maps to => https://my-app.com/ - Create
/pages/contact.vue
for your contact page => maps to => (https://my-app.com/contact - Create
/pages/customers.vue
for to display customers => maps to => https://my-app.com/customers
The directory structure in pages
..
pages/
--| index.vue
--| contact.vue
--| customers.vue
.. is equivalent to the below router file -
router: {
routes: [
{
path: '/',
component: 'pages/index.vue',
},
{
path: '/contact',
component: 'pages/contact.vue',
},
{
path: '/customers',
component: 'pages/customers.vue',
},
]
}
You can also have dynamic routes -
pages/
--| _id.vue
.. which is equivalent to => https://my-app.com/a1iDThis
.. or nested routes..
pages/
--| customers/
-----| _id.vue
-----| index.vue
--| contact.vue
--| index.vue
.. which will generate => -
- https://my-app.com/customers/c123
- https://my-app.com/customers/
- https://my-app.com/contact/
- https://my-app.com/
Using Route Middleware
Use middleware to perform dark magic on routes. You can protect routes and make them accessible only for authenticated users for example.
Create middleware
directory in Nuxt root folder, and create a new file called auth.js
therein.
|
|
The above code is doing two things -
- check whether current execution context is
client
(we don’t want this check to happen on server - our cookie/session variables exist in client browser ) - if current user is not logged in (provided by
isLoggedIn
), redirect to/login
page
Tell Nuxt about this middleware - edit nuxt.config.js
-
|
|
To use this middleware, just include the below code block in your page -
|
|
Now, Nuxt will redirect user to /login
page if not already authenticated (i.e., isLoggedIn
is false
).
Override Default Behaviour: Bring your own router
You can always assume more control in routing if you are still getting adjusted to the idea of “automatic routing”, or simply have too many things going on during routing.
Use router-module in your Nuxt project.
-
Install
npm i --save @nuxtjs/router
-
Add to build modules in
nuxt.config.js
1 2 3
export default { buildModules: ["@nuxtjs/router"], };
-
Create
router.js
in your Nuxt project and include the “normal” router code1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import Vue from "vue"; import Router from "vue-router"; import Index from "~/components/index"; import Contact from "~/components/contact"; Vue.use(Router); export function createRouter() { return new Router({ mode: "history", routes: [ { path: "/", component: Index }, { path: "/contact", component: Contact }, ], }); }