💚 Vue.js Intermediate

What are Vue Router navigation guards in detail?

Why Interviewers Ask This

This tests whether you can apply Vue.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

Vue Router navigation guards hook into the navigation process to allow, redirect, or cancel navigation. Global guards (on the router object): router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !store.isLoggedIn) { return "/login"; // redirect } return true; // allow }). Can return false (cancel), a route location object (redirect), or true/undefined (allow). next() legacy API still works but returning is cleaner. router.afterEach((to, from, failure) => { sendAnalytics(to.path); }). router.beforeResolve — called after all in-component guards and async route components are resolved. Per-route guards: defined on the route object: { path: "/admin", component: AdminView, beforeEnter(to, from) { if (!isAdmin) return "/403"; } }. Array of guards: beforeEnter: [checkAuth, checkPermission]. In-component guards (Options API): beforeRouteEnter(to, from, next) { next(vm => { vm.doSomething(); }); } — only guard that can access the component instance via callback; beforeRouteUpdate — when navigating to the same component with different params (/user/1 → /user/2); beforeRouteLeave — before leaving, use for unsaved changes warning. Composition API (setup): onBeforeRouteLeave((to, from) => { if (unsavedChanges) return false; });. Route meta: custom data on routes: meta: { requiresAuth: true, roles: ["admin"] } — use in guards for permission checking.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Vue.js answers easy to follow.