Vaadin Router automatically calls specific methods on your view Web Components during the navigation lifecycle. You do not need to extend a specific class; simply defining these methods is sufficient. Methods can be synchronous or return a Promise.
Navigation Guarding and Redirecting
Use these methods to intercept navigation, prevent it, or redirect the user:
onBeforeEnter(location, commands, router): Called before the outlet is updated.- Return
commands.prevent() (or a Promise resolving to it) to abort navigation. - Return
commands.redirect(path) (or a Promise resolving to it) to start a new navigation cycle to the new path.
onBeforeLeave(location, commands, router): Called when navigating away from the component.- Return
commands.prevent() to abort the navigation.
Post-Navigation Hooks
Use these methods for setup or cleanup after the DOM has been updated:
onAfterEnter(location, commands, router): Called asynchronously after connectedCallback() once the outlet has been updated with the new element.onAfterLeave(location, commands, router): Called when the component is being removed from the DOM. Note that this method cannot prevent navigation; the component is already being resolved for removal.
class MyView extends HTMLElement {
async onBeforeEnter(location, commands, router) {
const isAuthorized = await checkAuth();
if (!isAuthorized) {
return commands.redirect('/login');
}
}
onAfterEnter(location, commands, router) {
console.log('View entered:', location.pathname);
}
}