Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

VueJS - Vue Router Navigation Guards

Advanced Navigation Guard Techniques

Navigation guards in Vue Router are used to guard navigations by either redirecting it or canceling it. This guide covers advanced techniques for using navigation guards to control access to routes in your VueJS application.

Key Points:

  • Navigation guards provide hooks for before and after navigation.
  • They can be used to implement authentication, authorization, and other access control mechanisms.
  • Vue Router supports global, per-route, and in-component guards.

Types of Navigation Guards

Global Guards

Global guards are applied to every navigation in the application. They can be defined in the router configuration:


// router.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
});

router.beforeEach((to, from, next) => {
  // Perform some logic before navigation
  if (to.path === '/about') {
    console.log('Navigating to About page');
  }
  next();
});

router.afterEach((to, from) => {
  // Perform some logic after navigation
  console.log('Navigation completed');
});

export default router;
                

Per-Route Guards

Per-route guards are defined directly in the route configuration object. They are specific to the route they are defined on:


// router.js
const router = new Router({
  routes: [
    { 
      path: '/', 
      component: Home 
    },
    { 
      path: '/about', 
      component: About,
      beforeEnter: (to, from, next) => {
        // Perform some logic before entering the route
        if (auth.isAuthenticated()) {
          next();
        } else {
          next('/login');
        }
      }
    }
  ]
});
                

In-Component Guards

In-component guards are defined inside the component using the component's lifecycle hooks:


// About.vue



                

Advanced Techniques

Authentication and Authorization

Use navigation guards to implement authentication and authorization in your application:


// router.js
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const currentUser = auth.getCurrentUser();

  if (requiresAuth && !currentUser) {
    next('/login');
  } else if (to.path === '/login' && currentUser) {
    next('/');
  } else {
    next();
  }
});

// Route configuration
const router = new Router({
  routes: [
    { path: '/', component: Home },
    { 
      path: '/about', 
      component: About,
      meta: { requiresAuth: true }
    },
    { path: '/login', component: Login }
  ]
});
                

Fetching Data Before Navigation

Use navigation guards to fetch data before allowing navigation to a route:


// router.js
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.fetchData)) {
    fetchData(to.params.id)
      .then(data => {
        to.params.data = data;
        next();
      })
      .catch(error => {
        next(false);
      });
  } else {
    next();
  }
});

// Route configuration
const router = new Router({
  routes: [
    { path: '/', component: Home },
    { 
      path: '/details/:id', 
      component: Details,
      meta: { fetchData: true }
    }
  ]
});
                

Best Practices

Follow these best practices when using Vue Router navigation guards:

  • Keep Guards Simple: Keep the logic within navigation guards simple and focused on a single responsibility.
  • Use Meta Fields: Use route meta fields to define and check conditions for navigation guards.
  • Handle Errors Gracefully: Provide appropriate error handling and user feedback when navigation is interrupted or fails.
  • Document Guard Logic: Document the purpose and logic of each navigation guard to make the codebase easier to understand and maintain.
  • Avoid Duplicate Checks: Avoid duplicating authentication or authorization checks in multiple guards by centralizing the logic in global guards.

Summary

This guide provided an overview of advanced navigation guard techniques in VueJS, including global, per-route, and in-component guards. By understanding and utilizing these techniques, you can control access to routes, implement authentication and authorization, and improve the overall security and user experience of your VueJS application.