Middle
Have you worked with Vue Router? Tell me about Vue Router navigation hooks.
sobes.tech AI
Answer from AI
Vue Router provides several navigation hooks that allow you to execute code at different points in the routing lifecycle:
beforeEach(to, from, next)— a global hook called before each navigation. Can be used for authorization checks or to cancel navigation.beforeResolve(to, from, next)— called afterbeforeEachand before navigation confirmation, useful for asynchronous operations.afterEach(to, from)— called after navigation is complete, does not have anextparameter, used for logging or analytics.beforeEnter(to, from, next)— a local hook set in route configuration, triggered before entering a specific route.- Hooks in components:
beforeRouteEnter(to, from, next)— called before entering the route, component is not yet created.beforeRouteUpdate(to, from, next)— called when the route is updated, using the same component.beforeRouteLeave(to, from, next)— called before leaving the route.
Example of using a global hook:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login');
} else {
next();
}
});
These hooks allow flexible navigation management, ensuring security, data loading, and other tasks.