Computer scienceFrontendVue.jsVue Router

Nested routes

5 minutes read

Nested routes in Vue Router enable you to build complex and hierarchical navigation structures in Vue.js programs. They promote a more structured and modular design, making your code easier to maintain and browse through. For instance, imagine a dashboard sectioned for user profile and settings. Without nested routes, every single section would require its own route. However, with nested routes, these sections can exist as child routes under the 'dashboard' route, achieving a more logical and clean organization of components.

Understanding nested routes

Nested routes refer to building routes within other routes. It enables you to create a layered hierarchy of components that correspond to different URLs. With nested routes, you can segment your application into smaller, reusable components. This approach is handy for applications with complex layouts or multi-step user interfaces.

Let's consider a practical example:

// main.js
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import Main from './components/Main.vue';
import Cart from './components/Cart.vue';
import Orders from './components/Orders.vue';

// Define routes
     const routes = [
          {
            path: '/main',
            component: Main,
            children: [
               {
                  path: 'cart',
                  component: Cart
               },
               {
                   path: 'orders',
                   component: Orders
               }
            ]
          }
     ]

// Create router instance
    const router = createRouter({
        history: createWebHistory(),
        routes
    })

// Create Vue instance
    const app = createApp({})
    app.use(router)
    app.mount('#app')

To establish nested routes in Vue Router, you define your routes using the createRouter. Within the routes configuration, you can nest child routes using the children property. Each child route must have a path and a component associated with it.

In this example, the 'Main' route has orders and cart as its children. Vue will smoothly take care of the rendering of components based on the current route, making your application lively and responsive.

Using route components

Route components are the Vue.js components associated with specific routes. When you access a route, the corresponding component is rendered in the designated area of your program. It enables you to wrap up functionality and UI elements specific to every route.

For example, in an e-commerce application with nested routes for products. You can define a route for the product list page and a nested route for the product details page. The component for the product list page can display a collection of products, and the component for the product details page can show detailed information about a specific product.

// main.js
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import ProductList from './components/ProductList.vue';
import ProductDetails from './components/ProductDetails.vue';

const routes = [
  {
    path: '/products',
    component: ProductList,
    children: [
      {
        path: ':id',
        component: ProductDetails,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const app = createApp({});
app.use(router);
app.mount('#app');

In the code snippet above, we import the necessary components ProductList and ProductDetails and represent the routes using the Vue Router. The parent route /products takes responsibility for rendering the ProductList component. Inside this parent route, we define a nested route :id that matches the product details page. The :id parameter lets us dynamically pass the product ID to the ProductDetails component.

With this arrangement, when a user goes to /products, the ProductList component will be rendered. And when they go to /products/{productID}, the ProductDetails component will be rendered, displaying the detailed information for the specified product.

Besides the previous examples, there is an alternative syntax for defining routes. Here is an example of this syntax:

const router = new VueRouter({
     routes: [{ 
        path: '/products', component: ProductList,
        children: [
            {
              path: ':id',
              component: ProductDetails,
            },
          ] 
        }] 
    });

Here the routes are directly defined within the configuration object passed to the VueRouter constructor. This approach is more concise and suitable for smaller programs where the routes can be represented in a single file.

Both syntaxes, whether defining routes separately or within the configuration object, are valid and might be used depending on the specific requirements and preferences of the project.

Best practices for nested routes

Efficient use of nested routes comes with its own set of best practices. Here are some crucial practices that will help you maintain a clean and scalable codebase:

  • Keep the nesting level shallow: Generally, keeping the nesting level of your routes as shallow as possible is recommended. Heavily nested routes can make your code harder to understand. Try to structure your routes in a way that keeps the nesting level at a minimum.

    For instance, instead of having routes like:

    /dashboard/users/:id/posts/:postId/comments/:commentId

    Think about breaking the structure and using query parameters or separate routes for related resources:

    /dashboard/users/:id
    /dashboard/posts/:postId
    /dashboard/comments/:commentId
  • Use named views for complex layouts: When you have complex layouts that demand multiple views to be rendered simultaneously, consider using named views. Named views let you define several outlets within your layout where different components can be rendered depending on the current route.

    For instance, if you have a layout with a sidebar and a main content area:

    <router-view name="sidebar"></router-view>
    <router-view name="content"></router-view>

    Set your routes to render components into the suitable named views:

    {
      path: '/dashboard',
      components: {
        sidebar: SidebarComponent,
        content: ContentComponent
      },
      children: [
        // Child routes
      ]
    }

Conclusion

Nested routes in Vue Router offer a tool for organizing and structuring your software's navigation flow. They enable you to create a layered structure of components that match different URLs, promoting code reusability and maintainability.

We've examined how to set up nested routes, where each child route is defined with a path and a component within the parent route's 'children' property. We've also discussed the use of route components and examined best practices for using nested routes, emphasizing the importance of keeping the nesting level shallow to avoid code complexity and using named views for complex layouts that demand multiple components to be rendered at once.

How did you like the theory?
Report a typo