Vue Router: Implementing Navigation and Dynamic Routes in VueJS Applications

December 10, 2024By Rakshit Patel

Routing is a crucial aspect of modern web applications, enabling users to navigate between different pages or views seamlessly. Vue Router, the official router for Vue.js, provides a powerful and flexible way to implement navigation and dynamic routes in Vue applications. This article explains how to set up Vue Router, define static and dynamic routes, and enhance your app’s navigation experience.


What is Vue Router?

Vue Router is the official routing library for Vue.js, designed to handle navigation and map URLs to components. It supports:

  • Declarative routing
  • Nested and dynamic routes
  • Lazy loading of components
  • History mode for clean URLs

Installing Vue Router

For Vue 3

Install Vue Router using npm or yarn:


npm install vue-route
Project Setup

Import Vue Router in your project and configure it in main.js


import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import App from './App.vue';
const routes = [
    { path: '/', component: () => import('./views/Home.vue') },
    { path: '/about', component: () => import('./views/About.vue') }
];
const router = createRouter({
    history: createWebHistory(),
    routes
});
const app = createApp(App);
app.use(router);
app.mount('#app');

Defining Routes

Routes are mappings between URLs and components.

Basic Routes

A basic route object contains the path and the corresponding component.


const routes = [
    { path: '/', component: Home },
    { path: '/about', component: About }
];
Dynamic Routes

Dynamic routes are used when the path includes variable segments.

Example: Defining a Dynamic Route

const routes = [
    { path: '/user/:id', component: UserProfile }
];
Accessing Route Parameters

Inside the component, access dynamic parameters using $route.params:


<template>
    <div>User ID: {{ $route.params.id }}</div>
</template>
<script>
    export default {
        name: 'UserProfile'
    };
</script>

Nested Routes

Nested routes allow you to define child routes within a parent route.

Example: Nested Routes

const routes = [
  {
    path: "/dashboard",
    component: Dashboard,
    children: [
      { path: "settings", component: Settings },
      { path: "profile", component: Profile },
    ],
  },
];

 

Rendering Nested Routes

Use <router-view> in the parent component to render child components:


<template>
    <div>
        <h1>Dashboard</h1>
        <router-view />
    </div>
</template>


Navigation in Vue Router

Programmatic Navigation

Navigate to a route programmatically using the router.push method:


this.$router.push('/about');

For dynamic routes, pass parameters:


this.$router.push({ name: 'UserProfile', params: { id: 123 } });
Navigation Links

Use the <router-link> component for declarative navigation:


<template>
    <div>
        <router-link to="/">Home</router-link>
        <router-link to="/about">About</router-link>
    </div>
</template>     


Advanced Features

Route Guards

Route guards are used to control navigation based on conditions like authentication.

Global Guards

Define a global beforeEach guard:


router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth && !isAuthenticated()) {
        next('/login');
    } else {
        next();
    }
});
Per-Route Guards

Add guards to specific routes:

const routes = [
{
path: '/protected',
component: Protected,
meta: { requiresAuth: true }
}
];

Lazy Loading Components

Load components only when the route is accessed to improve performance.

const routes = [
{ path: '/about', component: () => import('./views/About.vue') }
];

Scroll Behavior

Customize scroll behavior when navigating between routes:


const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return {top: 0 };
        }
    }
});

Best Practices

  1. Organize Routes: Group routes in a separate routes.js file for maintainability.
  2. Use Route Names: Assign names to routes for easier programmatic navigation.
  3. Optimize Performance: Implement lazy loading for non-critical components.
  4. Secure Routes: Use route guards to protect sensitive routes.
  5. Test Routes: Verify navigation and dynamic behavior using automated tests.

Conclusion

Vue Router simplifies the process of implementing navigation and dynamic routes in Vue.js applications. From basic static routes to complex nested and dynamic routes, it offers robust features to manage navigation effectively.

By leveraging Vue Router’s capabilities like lazy loading, route guards, and scroll behavior, you can create seamless and efficient navigation experiences for your users. Whether you’re building a simple single-page application or a large-scale web platform, Vue Router is an indispensable tool in your Vue.js toolkit.

Rakshit Patel

Author ImageI am the Founder of Crest Infotech With over 15 years’ experience in web design, web development, mobile apps development and content marketing. I ensure that we deliver quality website to you which is optimized to improve your business, sales and profits. We create websites that rank at the top of Google and can be easily updated by you.

CATEGORIES