In Vue Router, navigation guards are functions that are executed before or after navigation to a route occurs. They allow developers to control and customize the navigation behavior of their Vue.js applications. Navigation guards provide hooks at different stages of the navigation process, allowing developers to perform tasks such as authentication, authorization, data fetching, and route validation.

There are three types of navigation guards in Vue Router.

Global Navigation Guards

These guards are applied to all routes in the application and are defined at the root level of the router configuration. They include beforeEach, beforeResolve, and afterEach.

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [...],
});

router.beforeEach((to, from, next) => {
  // Authentication check
  if (!isAuthenticated) {
    next('/login'); // Redirect to login page if not authenticated
  } else {
    next(); // Proceed with navigation
  }
});

router.afterEach((to, from) => {
  // Logging or analytics
  console.log(`Navigated from ${from.path} to ${to.path}`);
});

export default router;

Per-Route Navigation Guards

These guards are defined within the route configuration and apply only to specific routes. They include beforeEnter, beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave.

const router = new VueRouter({
  routes: [
    {
      path: '/profile',
      component: Profile,
      beforeEnter: (to, from, next) => {
        // Authorization check
        if (!hasPermission) {
          next('/403'); // Redirect to forbidden page if not authorized
        } else {
          next(); // Proceed with navigation
        }
      },
    },
  ],
});

In-Component Navigation Guards

These guards are defined within the component options and apply only to the component they are defined on. They include beforeRouteEnter, beforeRouteUpdate, and beforeRouteLeave.

export default {
  name: 'Profile',
  beforeRouteEnter(to, from, next) {
    // Logic before entering the route
    next();
  },
  beforeRouteUpdate(to, from, next) {
    // Logic before updating the route
    next();
  },
  beforeRouteLeave(to, from, next) {
    // Logic before leaving the route
    next();
  },
};

Navigation guards provide a powerful mechanism for controlling and customizing the navigation behavior of Vue.js applications, allowing developers to create complex navigation flows and ensure the security and consistency of their applications.