Introduction to Navigation Guards in Vue Router

Navigation guards in Vue Router allow you to control and guard navigation within your Vue.js application. Before and after hooks are essential parts of navigation guards that enable you to execute code before and after route navigation. In this guide, we'll explore how to use these hooks to secure, control, and enhance navigation in your Vue.js application.


Before Route Navigation - beforeEach Guard

The beforeEach guard is a before-enter guard that is executed before navigating to a new route. You can use it to perform checks, authentication, and other tasks before allowing access. Here's an example of using the beforeEach guard:


import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{ path: '/public', component: PublicComponent },
{ path: '/secure', component: SecureComponent },
],
});
router.beforeEach((to, from, next) => {
// Check if the route requires authentication
if (to.path === '/secure' && !isAuthenticated()) {
// Redirect to the login page
next('/login');
} else {
// Continue to the requested route
next();
}
});
function isAuthenticated() {
// Implement your authentication logic here
return false; // Replace with actual logic
}
const app = new Vue({
router,
}).$mount('#app');

In this example, we use the beforeEach guard to check if the user is authenticated before allowing access to the "secure" route.


After Route Navigation - afterEach Guard

The afterEach guard is executed after route navigation is complete. It can be used for tasks like tracking page views or handling cleanup. Here's an example of using the afterEach guard:


router.afterEach((to, from) => {
// Track the page view
trackPageView(to.path);
// Perform other post-navigation tasks
});
function trackPageView(path) {
// Implement your page view tracking logic here
console.log(`Page view: ${path}`);
}

In this example, we use the afterEach guard to track page views and execute post-navigation tasks.


Conclusion

Navigation guards with before and after hooks are vital for controlling route navigation and enhancing user experience in your Vue.js application. By effectively using these hooks, you can secure routes, implement authentication, and perform post-navigation tasks, making your application more powerful and user-friendly.