Course Content
VUE Tutorial
About Lesson

Navigation Guards

Vue.js, a progressive JavaScript framework, offers powerful features for building robust single-page applications. One such feature that enhances the navigation experience is Navigation Guards. Let’s delve into what navigation guards are and how they can be utilized in Vue applications.

What are Navigation Guards?

Navigation guards are hooks provided by Vue Router, allowing developers to execute functions at specific points in the navigation process. These hooks enable you to control the navigation flow, guarding routes based on certain conditions.

Types of Navigation Guards

1. Global Guards

Global guards are applied to all routes in your application. They include:

beforeEach

Executed before each route change. Useful for authentication checks or global navigation validation.

router.beforeEach((to, from, next) => {
// Your logic here
next();
});
beforeResolve

Triggered after beforeEach and before the route is resolved.

router.beforeResolve((to, from, next) => {
// Your logic here
next();
});
afterEach

Runs after each successful navigation.

router.afterEach((to, from) => {
// Your logic here
});

2. Per-Route Guards

Per-route guards are specific to a particular route and are defined in the route configuration.

beforeEnter

Executed before entering the route.

const route = {
path: '/example',
component: ExampleComponent,
beforeEnter: (to, from, next) => {
// Your logic here
next();
},
};
beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave

These guards are used within the component.

beforeRouteEnter(to, from, next) {
// Your logic here
next();
}

Use Cases

1. Authentication Control

Use navigation guards to check if a user is authenticated before allowing access to certain routes.

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !auth.isAuthenticated()) {
next('/login');
} else {
next();
}
});

2. Data Fetching

Ensure data is fetched before entering a route using beforeRouteEnter a guard.

beforeRouteEnter(to, from, next) {
fetchData()
.then((data) => {
next(vm => {
vm.data = data;
});
})
.catch(() => {
next('/error');
});
}