Named Routes in Nuxt.js

Tutorial 4 of 5

Named Routes in Nuxt.js Tutorial

1. Introduction

In this tutorial, we will delve into the use of named routes in Nuxt.js. Named routes are a way to uniquely identify routes in your application, which makes it easier to navigate within your app.

By the end of this tutorial, you will be able to:

  • Understand what named routes are and why they are useful in Nuxt.js
  • Create named routes in your Nuxt.js application
  • Use named routes for navigation

Prerequisites:

  • Basic knowledge of JavaScript
  • Familiarity with Vue.js and Nuxt.js
  • A Nuxt.js project set up on your local machine

2. Step-by-Step Guide

Nuxt.js automatically generates the vue-router configuration by parsing your Vue files inside the pages directory. To create a named route, you simply have to create a .vue file in the pages directory.

For example, if you create a file named about.vue in the pages directory, Nuxt.js will automatically create a route named 'about' that maps to this file.

To navigate to a named route, you can use the <nuxt-link> component's to prop or the router.push() method.

3. Code Examples

Example 1: Creating a Named Route

  1. Create a new file about.vue in the pages directory:
<template>
  <div>
    <h1>About</h1>
    <p>This is the about page</p>
  </div>
</template>

This will automatically create a route named 'about' that maps to this file.

Example 2: Navigating to a Named Route

  1. You can use the <nuxt-link> component to navigate to the 'about' page:
<nuxt-link to="/about">About</nuxt-link>
  1. Alternatively, you can use the router.push() method:
this.$router.push({ name: 'about' });

4. Summary

In this tutorial, we learned about named routes in Nuxt.js, how to create them, and how to navigate to them using either the <nuxt-link> component or the router.push() method. As next steps, you might want to explore more about dynamic routes in Nuxt.js.

5. Practice Exercises

  1. Exercise 1: Create a new named route for a "Contact" page and create a link to this page from the "About" page.

Solution:

// pages/contact.vue
<template>
  <div>
    <h1>Contact</h1>
    <p>This is the contact page</p>
  </div>
</template>

// pages/about.vue
<template>
  <div>
    <h1>About</h1>
    <p>This is the about page</p>
    <nuxt-link to="/contact">Contact</nuxt-link>
  </div>
</template>
  1. Exercise 2: Create a button in the "About" page that navigates to the "Contact" page when clicked.

Solution:

// pages/about.vue
<template>
  <div>
    <h1>About</h1>
    <p>This is the about page</p>
    <button @click="goToContact">Go to Contact</button>
  </div>
</template>

<script>
export default {
  methods: {
    goToContact() {
      this.$router.push({ name: 'contact' });
    },
  },
};
</script>

Keep practicing and exploring more complex routing scenarios. Happy coding!