Cancelling Navigation
Part of the Routing and State section of Coddy's Vue journey. Lesson 29 of 55.
A global navigation guard runs before a navigation is confirmed. Returning false cancels the attempt, so the existing page remains. Read the destination argument to decide whether the attempted route is allowed.
router.beforeEach(to=>{
if(to.meta.needsTicket && !hasTicket.value) return false;
});Returning nothing permits navigation in this synchronous guard. Keep public destinations reachable and check the current permission value on every attempt rather than capturing an initial snapshot. Client guards control user experience; protected server resources still require server-side authorization.
Challenge
MediumRegister a global beforeEach guard that returns false when the destination has meta.requiresPass and the supplied hasPass ref is false. Calendar requires a pass; Home and Help are public. The checkbox input#pass changes this session-only flag. A denied navigation must stay on the current view and path. This UI gate is not server authorization.
Keep the supplied route readout and bootstrap files.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Routing practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Routing and State
4Query State
Reading Query ValuesCommitting Search QueriesPreserving Other FiltersNormalizing Query NumbersRecap: Catalog Filters2Navigation Actions
Navigation from HandlersReplacing HistoryHistory TravelCurrent Navigation LinksRecap: Save and Review5Nested Layouts
Parent and Child OutletsDefault Child ViewsRelative Child PathsAncestor Navigation StateRecap: Library Workspace8Store Design
Setup Store StructurePatching Related StateResetting Store StateComposing Related StoresRecap: Trip Pack11Workshop Planner Project
Planner RoutesShared Reservations3Dynamic Routes
Path ParametersReactive Route SelectionRoute Parameters as PropsMissing Route RecordsRecap: Equipment Routes6Route Policies
Redirecting Old PathsUnmatched PathsRoute MetadataCancelling NavigationRecap: Club Destinations