Protecting Unsaved Drafts
Part of the Routing and State section of Coddy's Vue journey. Lesson 49 of 55.
A component leave guard can stop navigation while its local draft is unsaved. Register onBeforeRouteLeave during setup and return false when the draft differs from the saved value. This rule belongs to the editor instance rather than every route in the app.
const dirty=computed(()=>draft.value!==saved.value);
onBeforeRouteLeave(()=>{
if(dirty.value)return false;
});Give the user a visible way to resolve the condition, such as Save or Discard. Saving updates the committed value, while discarding restores the draft. The guard then allows leaving naturally. This avoids making a user trapped behind an invisible cancellation rule.
Challenge
MediumUse onBeforeRouteLeave in the editor to cancel leaving while its local draft differs from its saved value. Start with Hello. Show Unsaved or Saved in p#dirty. Save copies draft to saved; Discard restores draft from saved. Either action makes leaving possible. This task deliberately uses a visible Save/Discard workflow instead of a browser confirmation dialog.
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 Filters7Pinia Options Stores
Shared Store StateDerived Store GettersStore Actions and BoundsExtracting Reactive FieldsRecap: Seat Counter10Guarded Workflows
Store-Aware Access GuardsReturning After Sign-InNested Access PoliciesProtecting Unsaved DraftsRecap: Museum Pass2Navigation 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 Reservations