Committing Search Queries
Part of the Routing and State section of Coddy's Vue journey. Lesson 17 of 55.
A draft input and a committed query serve different purposes. Keep the draft in a ref while the person types, then navigate when they submit. This avoids adding a history entry for every keystroke.
const draft=ref('');
function submit(){
const author=draft.value.trim();
router.push({path:'/library',query:author?{author}:{}});
}Pass query data as an object so the router handles URL encoding. Removing an optional filter means omitting its key from the next query. Decide whether submission should push a navigable checkpoint or replace the current entry; this example deliberately pushes.
Challenge
MediumKeep typing in input#draft local until button#apply is clicked. On Apply search, trim the draft and push the root route with query q. An empty trimmed draft removes the key entirely. Show the committed query as Search: [value] in p#term; typing alone must not change it.
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 Reservations