Vue.js / Vue Router and Navigation

Using Dynamic and Nested Routes

In this tutorial, we'll explore dynamic and nested routes in Vue.js. You'll learn how to create routes that can change based on user input, and how to build hierarchical site stru…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers navigation and routing in Vue applications.

1. Introduction

The goal of this tutorial is to provide you with a clear understanding of how to use dynamic and nested routes in Vue.js. This tutorial aims to help you create more flexible and organized applications using Vue's powerful routing capabilities.

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

  • Create dynamic routes that can change based on user input
  • Implement nested routes to build hierarchical site structures
  • Understand how these concepts can be applied in real-world applications

Prerequisites:

  • Basic understanding of Vue.js
  • Familiarity with JavaScript and HTML

2. Step-by-Step Guide

Dynamic Routes

Dynamic routes are routes that can change based on user input or other factors. In Vue.js, you can create dynamic routes by using the :id syntax in your route path.

{
  path: '/user/:id',
  component: User
}

In this case, :id is a placeholder for whatever value is passed in the URL after /user/.

Nested Routes

Nested routes allow you to create more complex interfaces where certain parts of your app are persistent while others change dynamically. This is achieved by creating "child" routes within "parent" routes.

{
  path: '/user/:id',
  component: User,
  children: [
    {
      path: 'profile',
      component: UserProfile
    },
    {
      path: 'posts',
      component: UserPosts
    }
  ]
}

In this example, UserProfile and UserPosts are child routes of the User parent route. When the /user/:id/profile or /user/:id/posts URLs are visited, the corresponding child component will be displayed.

3. Code Examples

Example 1: Dynamic Route

// Define your User component
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

// Define your route
const routes = [
  { path: '/user/:id', component: User }
]

// Create the router instance
const router = new VueRouter({
  routes
})

// Create and mount the root instance.
const app = new Vue({
  router
}).$mount('#app')

// Now the app has started!

When you visit /user/123, the rendered HTML will be <div>User 123</div>.

Example 2: Nested Route

// Define your components
const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}

const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }

// Define your routes
const routes = [
  { 
    path: '/user/:id', 
    component: User,
    children: [
      {
        path: 'profile',
        component: UserProfile
      },
      {
        path: 'posts',
        component: UserPosts
      }
    ]
  }
]

// Create the router instance
const router = new VueRouter({
  routes
})

// Create and mount the root instance.
const app = new Vue({
  router
}).$mount('#app')

// Now the app has started!

When you visit /user/123/profile, the rendered HTML will be the User component with the UserProfile component nested inside.

4. Summary

In this tutorial, we've learned how to create dynamic routes and nested routes in Vue.js. These concepts allow us to create more flexible and structured applications.

Further learning can include exploring more advanced routing concepts in Vue.js, such as named routes and route guards. You can find more information in the Vue Router documentation.

5. Practice Exercises

  1. Create a dynamic route for a Blog component where each post can be accessed with a unique :id.

  2. Build on the previous exercise by adding nested routes for comments and author under each blog post.

  3. Experiment with adding route guards to restrict access to certain routes.

Solutions and further practice can be found by exploring the Vue Router documentation and experimenting with different routing configurations in your own Vue.js applications.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Image Converter

Convert between different image formats.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help