Vue Router Essentials: Navigating Pages in Vue.js Applications

By Maulik Paghdal

16 Dec, 2024

Vue Router Essentials: Navigating Pages in Vue.js Applications

Introduction

When building single-page applications (SPAs) with Vue.js, managing navigation between different views or pages is crucial. Vue Router, the official router for Vue.js, simplifies this process by offering a powerful and flexible solution for handling routes. Whether you’re creating a simple blog or a complex application, understanding Vue Router is key to building seamless user experiences.

In this blog, we’ll explore the fundamentals of Vue Router and demonstrate how to set up and manage navigation in Vue.js applications.

Setting Up Vue Router

To use Vue Router, you must first install it in your Vue.js project.

Installation

If you haven’t already installed Vue Router, you can do so via npm or yarn:

npm install vue-router
# or
yarn add vue-router

Step 2: Defining Routes

Create a router.js file to define your routes. Each route maps a URL path to a Vue component.

import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

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

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

export default router;

Step 3: Integrating Vue Router

In your main.js file, import and use the router.

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

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

Dynamic Routing

Dynamic routing allows you to create routes with parameters, enabling flexibility in handling different data.

Example

Define a route with a dynamic segment using the :id parameter:

const routes = [
  { path: '/user/:id', component: UserDetails },
];

Access the dynamic parameter in your component using $route.params:

<template>
  <div>
    <h1>User ID: {{ userId }}</h1>
  </div>
</template>

<script>
export default {
  computed: {
    userId() {
      return this.$route.params.id;
    },
  },
};
</script>

Navigation guards help control access to routes, ensuring secure and predictable navigation.

Example

Use a beforeEach guard to check authentication before accessing a protected route:

router.beforeEach((to, from, next) => {
  const isAuthenticated = false; // Replace with actual authentication check
  if (to.path === '/protected' && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

Lazy Loading Routes

To improve performance, use lazy loading to load components only when required:

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

Nested Routes

Vue Router supports nested routes to create a hierarchical structure:

const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    children: [
      { path: 'stats', component: Stats },
      { path: 'settings', component: Settings },
    ],
  },
];

Use the <router-link> component to navigate between routes without reloading the page:

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

To navigate programmatically, use this.$router.push():

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

Conclusion

Vue Router is an essential tool for building single-page applications in Vue.js. By mastering its features like dynamic routing, navigation guards, and lazy loading, you can create seamless, user-friendly applications. Start experimenting with Vue Router today to enhance your Vue.js projects!