Vue Router navigation guards are functions that allow you to control and customize the navigation behavior of your Vue.js applications. They are applied to routes and can be used for tasks such as authentication, authorization, and data fetching. Vue Router provides several types of navigation guards, and each type serves a different purpose. Here are the main navigation guards in Vue Router:
Global Guards:
beforeEach(to, from, next)
: Called before each navigation. You can use this guard to perform tasks like authentication checks.beforeResolve(to, from, next)
: Similar to beforeEach
, but it is called after the navigation is confirmed.afterEach(to, from)
: Called after each navigation. Useful for tasks that need to be performed after the navigation.Per-Route Guards:
beforeEnter(to, from, next)
: Called before the route is entered. It allows you to add specific guards to individual route configurations.beforeRouteEnter(to, from, next)
: Called before the component associated with the route is created and added to the DOM.beforeRouteUpdate(to, from, next)
: Called when the route is updated, but the associated component remains the same.beforeRouteLeave(to, from, next)
: Called before the route is left. Useful for cleaning up resources or preventing navigation.Here's an example of how to use these navigation guards in a Vue.js application:
javascript// main.js
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: '/',
component: Home,
beforeEnter: (to, from, next) => {
// Perform authentication check or other tasks
if (/* authenticated */) {
next();
} else {
next('/login');
}
},
},
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
// Another route-specific guard
// Check if the user has the required role, for example
if (/* userHasRequiredRole */) {
next();
} else {
next('/unauthorized');
}
},
},
],
});
// Global navigation guard
router.beforeEach((to, from, next) => {
// Perform some global tasks before each navigation
next();
});
new Vue({
render: (h) => h(App),
router,
}).$mount('#app');
In this example, beforeEach
is a global guard that is applied to all routes, while beforeEnter
is a per-route guard applied to specific routes. You can use these guards to implement various navigation-related logic in your Vue.js application.