Introduction to Nuxt.js Routing

Tutorial 1 of 5

Introduction

Goals

In this tutorial, you will learn the basics of routing in Nuxt.js, a robust framework for building Vue.js applications. One of the unique features of Nuxt.js is its automated routing system, which we will focus on in this tutorial.

What You Will Learn

By the end of this tutorial, you will understand how Nuxt.js generates routes automatically based on your Vue file structure. You will also learn how to create dynamic routes, nested routes, and named views in Nuxt.js.

Prerequisites

Before proceeding with this tutorial, you should have a basic understanding of Vue.js and JavaScript. Familiarity with ES6 syntax (like arrow functions, modules, etc.) and Vue Router will be beneficial but not mandatory.

Step-by-Step Guide

Nuxt.js automatically creates a vue-router configuration by parsing your file tree of Vue files inside the pages directory.

For example, the file tree:

pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue

Will automatically generate:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'user',
      path: '/user',
      component: 'pages/user/index.vue'
    },
    {
      name: 'user-one',
      path: '/user/one',
      component: 'pages/user/one.vue'
    }
  ]
}

Code Examples

Example 1: Basic Routing

  1. Create a new file index.vue in your pages directory with the following content:
<template>
  <h1>Hello, Nuxt.js!</h1>
</template>

This will automatically create a route to the home page '/'. When you navigate to your application's home page, you should see "Hello, Nuxt.js!" displayed.

Example 2: Generating Dynamic Routes

  1. Create a new file _slug.vue in your pages directory:
<template>
  <h1>{{ $route.params.slug }}</h1>
</template>

This will match any route like '/abc', '/xyz', etc., and display the route path in the page.

Summary

In this tutorial, we've learned about Nuxt.js routing, how it automatically generates routes based on the Vue file structure, and how to create dynamic routes. For further learning, you can read about more advanced routing concepts like nested routes and named views in the Nuxt.js documentation.

Practice Exercises

  1. Try creating a nested route by adding a Vue file in a folder within the pages directory.
  2. Try creating a dynamic nested route.
  3. Experiment with different naming conventions and observe how the routes are generated.

Solutions:

  1. Create pages/blog/index.vue. This will generate a '/blog' route.
  2. Create pages/blog/_post.vue. This will generate a dynamic route like '/blog/my-first-post'.
  3. Files and folders prefixed with an underscore generate dynamic routes, while those without are static routes.

Remember, practice is key to mastering Nuxt.js routing, so keep experimenting with different Vue file structures and see how the routes are generated.

Additional Resources