In this article, we are going to learn how routing works in NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of a similar purpose, based on React.js.
Create NuxtJS Application:
Step 1: You can create a new Nuxt.js project using the below command:
npx create-nuxt-app gfg
Step 2: Now navigate to your app using the following command:
cd gfg
Project Structure: It will look like this.
Routing: In frameworks like Nuxt.js, Next.Jj, and React.js we usually have more than one page. So we need a router to navigate between different pages of the application. The process of adding a router in the application in order to navigate between pages is called routing.
Automatic Routes: In other Vue applications, we have to manually create and add different routes in the router configuration file. But in Nuxt.js, you don’t have to manually create a router configuration file. It automatically creates vue-router configuration and adds every route of the application to the file. Whenever you create a new page the route of that will be automatically get added to the configuration file.
Example: Let’s create a new page named ‘gfg.vue’ with the below content:
gfg.vue
<template> <div> <h3>This is the GFG Page.</h3> </div> </template> |
index.vue
<template> <div> <h3>This is the Home Page.</h3> </div> </template> |
Start the application: Use the below command to start the application.
npm run dev
Output:
Navigation: We can add navigation in the Nuxt.js application using the NuxtLink component. You don’t need to import this component into your file.
Example: Let’s change the content of ‘gfg.vue’ with the below content:
gfg.vue
<template> <div> <h3>This is the GFG Page.</h3> <NuxtLink to= "/" > Go to HomePage </NuxtLink> </div> </template> |
index.vue
<template> <div> <h3>This is the Home Page.</h3> <NuxtLink to= "/gfg" > Go to GFG Page </NuxtLink> </div> </template> |
Start the application: Use the below command to start the application.
npm run dev
Output:
Reference: https://nuxtjs.org/docs/get-started/routing