Route Guards Lifecycle and Usage Tips
In the Nuxt framework, route guards control navigation flow through predefined lifecycle hooks such as beforeEach, beforeRouteEnter, beforeRouteLeave, etc. These hooks are triggered in a specific order to ensure necessary logic executes before routing changes occur:
beforeEach: A global guard used to intercept all navigation events; it allows customizing the navigation behavior globally.beforeRouteEnter: Triggered just before entering a route, allowing access to component props or injected context data.beforeRouteLeave: Triggered immediately before leaving a route; commonly used to prevent users from navigating away without confirmation (e.g., unsaved changes).beforeEnter: Only triggered when switching routes with dynamic parameters; useful for validating parameter values at the transition point.
Usage Tips
- Permission Verification : Retrieve component props via
beforeRouteEnterand combine them with user permission data to make access decisions. - Data Caching : Use
beforeRouteUpdateto cache data during route updates, avoiding redundant API requests. - Global Interception : Intercept all navigation changes using
beforeEachfor unified handling of authentication states or global permission checks. - Route Meta Information : Set the
metaproperty in route configurations and use guard logic dynamically to control access permissions based on metadata. - Nested Guard Execution Order: In nested routes, ensure that
beforeRouteLeavetriggers afterbeforeRouteEnterto maintain correct execution flow.
Practical Example
// Example: Dynamic Route Parameter Validation
const routes = [
{
path: '/user/:id',
meta: { requiresAuth: true },
components: {
default: () => import('./views/User.vue'),
header: () => import('./components/Header.vue')
}
}
];
// Route Guard Configuration
export default {
beforeRouteEnter(to, from, next) {
if (!localStorage.getItem('token')) {
// Redirect to login page if no token exists
next('/login');
} else {
next();
}
},
beforeRouteUpdate(to, from, next) {
const userId = to.params.id;
let cachedUserId = localStorage.getItem('cachedUser');
// Cache the user ID if it differs from stored value
if (userId !== cachedUserId) {
localStorage.setItem('cachedUser', userId);
}
next();
}
};
Combining Route Guards
- Combination of Navigation and Component Guards : Use
beforeEachto intercept global navigation events, then apply component-specific guards for detailed route logic. - Lifecycle Management for Dynamic Parameters: Retrieve parameters in
beforeRouteEnter, update related data inbeforeRouteUpdate, and execute follow-up actions viaafterRouteUpdate. - Dynamic Control of Route Meta Information : Combine the
metaproperty with guard conditions to implement conditional access restrictions dynamically based on route metadata.