In Vue Router, implementing route protection is primarily achieved through navigation guards. These are hook functions that execute before route navigation occurs, enabling operations such as authentication checks, data preloading, and conditional navigation. Vue Router provides several types of navigation guards, including global guards, route-level guards, and component-level guards.
Global Guards
Global guards are designed for logic that must run before navigating to any page, such as user authentication.
Example:
javascriptrouter.beforeEach((to, from, next) => { // Check if the user is logged in if (to.matched.some(record => record.meta.requiresAuth)) { if (!auth.isLoggedIn()) { // Redirect to login page if not authenticated next({ path: '/login' }); } else { // Proceed to target page if authenticated next(); } } else { next(); // Ensure to call next() } });
Route-Level Guards
Route-level guards are invoked only when a specific route is accessed.
Example:
javascriptconst router = new VueRouter({ routes: [ { path: '/profile', component: Profile, beforeEnter: (to, from, next) => { if (!auth.isLoggedIn()) { next({ path: '/login' }); } else { next(); } } } ] });
Component-Level Guards
Component-level guards allow you to define guards directly within the route component.
Example:
javascriptexport default { beforeRouteEnter(to, from, next) { if (!auth.isLoggedIn()) { next({ path: '/login' }); } else { next(); } } };
By utilizing these guards, you can control user navigation based on login status or other conditions to implement route protection.