vuejs-navegacion-programatica-guards

Programmatic Navigation and Guards in Vue.js

  • 3 min

Programmatic navigation refers to the ability to change routes through code instead of clicking a <router-link>.

This is very useful in certain circumstances. For example, when we need to redirect the user after certain actions (like a successful login or form validation).

Programmatic Navigation Methods

Vue Router provides several methods for performing programmatic navigation:

MethodDescription
router.push()Navigates to a new route and adds an entry to the browser’s history.
router.replace()Similar to push, but does not add a new entry to the history.
router.go()Navigates forward or backward in the history (similar to the browser’s native history).
// In a component method
methods: {
  redirectToHome() {
    this.$router.push('/home');
  }
}

This code redirects the user to the /home route when the redirectToHome method is called.

// In a component method
methods: {
  replaceCurrentRoute() {
    this.$router.replace('/new-route');
  }
}

This code replaces the current route with /new-route without adding a new entry to the history.

// In a component method
methods: {
  goBack() {
    this.$router.go(-1); // Navigates backward in the history
  }
}

This code navigates backward in the browser’s history.

Route Guards

Route guards are functions that run before, during, or after navigation. They are useful for controlling access to specific routes, such as authentication.

Vue Router offers several types of guards:

TypeScope
Global guardsAll routes
Per-route guardsSpecific routes
In-component guardsIndividual components

Global guards are defined in the router instance and affect all routes. The most common are:

  • beforeEach: Runs before each navigation.
  • beforeResolve: Runs after all component guards and async components have been resolved.
  • afterEach: Runs after each navigation.
const router = new VueRouter({
  routes: [
    // Route definitions
  ]
});

router.beforeEach((to, from, next) => {
  const isAuthenticated = checkAuth(); // Function that checks authentication
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login'); // Redirects to login if not authenticated
  } else {
    next(); // Continues with the navigation
  }
});

This code checks whether the user is authenticated before allowing access to routes that require authentication.

Per-route guards are defined directly in the configuration of a specific route. The most common are:

  • beforeEnter: Runs before entering the route.
const router = new VueRouter({
  routes: [
    {
      path: '/dashboard',
      component: Dashboard,
      beforeEnter: (to, from, next) => {
        const isAdmin = checkAdmin(); // Function that checks if the user is an admin
        if (!isAdmin) {
          next('/unauthorized'); // Redirects if not an admin
        } else {
          next(); // Continues with the navigation
        }
      }
    }
  ]
});

This code checks if the user is an administrator before allowing access to the /dashboard route.

In-component guards are defined within components and allow for more granular control. The most common are:

  • beforeRouteEnter: Runs before the component is mounted.
  • beforeRouteUpdate: Runs when the route changes but the component is reused.
  • beforeRouteLeave: Runs before leaving the component.
export default {
  name: 'EditProfile',
  beforeRouteLeave(to, from, next) {
    if (this.unsavedChanges) {
      const confirmLeave = confirm('You have unsaved changes. Are you sure you want to leave?');
      if (confirmLeave) {
        next(); // Continues with the navigation
      } else {
        next(false); // Cancels the navigation
      }
    } else {
      next(); // Continues with the navigation
    }
  }
};

This code shows a confirmation message if the user attempts to leave the page with unsaved changes.