Until now, every navigation in Colmena was started by the user clicking a <RouterLink>. But there are many situations in which it is the code that decides to change screen: after a form has been submitted successfully, when clicking a button that first does something and then navigates, when going back from a spec sheet or when reacting to an error. For this, Vue Router offers a programmatic navigation API: router.push, router.replace and movements through the history. In this lesson you will study it in depth, including the promise that each navigation returns and how to detect the ones that fail. In the second part you will learn to use the other half of the URL, the query parameters (?floor=2&sort=price-asc), to store a screen's state, such as the catalogue's filters, so that it survives reloads, can be shared and works with the Back button.
Contents
useRouter(): the router from coderouter.pushrouter.replace- Moving through the history:
go,backandforward RouterLinkorrouter.push?- Navigation is a promise: navigation failures
- Query parameters: reading
route.query - Writing the query and converting types
- Case study: navigating from code and filters in the URL
useRouter(): the router from code
useRouter(): the router from codeIn 04-03 you used useRoute() to read the current route. To navigate, you need the other piece, the router itself, which you obtain with useRouter():
import { useRoute, useRouter } from 'vue-router'
const route = useRoute() // where I am
const router = useRouter() // how I moveuseRoute() |
useRouter() |
|
|---|---|---|
| Returns | The current route: a reactive object (params, query, name...) |
The router instance: the same one that src/router/index.js exports |
| Used for | Reading the URL | Navigating (push, replace, back...), resolving addresses, inspecting the routes |
| In the template | $route |
$router |
| In the Options API | this.$route |
this.$router |
Like useRoute(), useRouter() is called at the top level of <script setup>. Outside components (in any JavaScript module), you can import the router directly: import router from '@/router'. This is useful, for example, so that the code that calls the API can take the user to the sign-in screen when the server responds that the session has expired.
router.push
router.pushrouter.push navigates to a new address by adding an entry to the history, exactly as a <RouterLink> does when it is clicked. In fact, RouterLink calls router.push under the hood. It accepts the same destinations as the to prop:
// 1. A string with the path
router.push('/rooms')
// 2. An object with a path
router.push({ path: '/rooms/nectar' })
// 3. An object with a name and params (the recommended form)
router.push({ name: 'room-detail', params: { id: 'nectar' } })
// 4. With query parameters → /rooms?floor=2
router.push({ name: 'rooms', query: { floor: 2 } })
// 5. With an anchor → /rooms/nectar#equipment
router.push({ name: 'room-detail', params: { id: 'nectar' }, hash: '#equipment' })
// 6. Relative to the current route: same route, different query
router.push({ query: { ...route.query, sort: 'price-asc' } })Note a few rules:
paramsis ignored if you usepath:{ path: '/rooms', params: { id: 'nectar' } }leads to/rooms. With params, usename, or write the complete path inpath.- The
paramsmust correspond to the route's params. You cannot "sneak" arbitrary data intoparamsfor the next screen: Vue Router discards it. To pass options, use the query. - A destination with neither
pathnorname(case 6) is relative to the current route: it keeps the route and its params, and replaces the query with the one you specify. That is why the current query is copied with...route.queryif you want to keep the rest of it.
router.replace
router.replacerouter.replace navigates just like push, but it replaces the current history entry instead of adding a new one (under the hood it uses history.replaceState, which you saw in 04-01):
router.replace({ name: 'rooms', query: { floor: 2 } })
// equivalent:
router.push({ name: 'rooms', query: { floor: 2 }, replace: true })In a <RouterLink>, the replace prop has the same effect. When is it appropriate?
- When the previous screen should not be a destination for Back: after signing in, the login screen; after an automatic redirect.
- When a state that changes often is reflected in the URL (filters, sort order, tab): each change should not add an entry to the history, or the user would have to click Back twenty times to leave the screen.
flowchart LR
subgraph push["With push (3 filter changes)"]
direction LR
A1["/"] --> A2["/rooms"] --> A3["?floor=1"] --> A4["?floor=2"] --> A5["?floor=3"]
end
subgraph replace["With replace (3 filter changes)"]
direction LR
B1["/"] --> B2["/rooms?floor=3"]
end
- Moving through the history:
go, back and forward
go, back and forwardThey are equivalent to the browser's buttons:
router.back() // like clicking Back: router.go(-1)
router.forward() // like clicking Forward: router.go(1)
router.go(-2) // two steps back
router.go(0) // does NOT reload: it does nothing usefulIf there are not as many entries as you ask for, nothing happens (silently). This raises a typical problem with "Back" buttons: if the user opened a room's spec sheet from a shared link, there is no previous screen inside the application, and router.back() would take them out to the page they came from (or do nothing). Vue Router stores information about each entry in window.history.state; in particular, history.state.back contains the previous address inside the application, or null if there is none:
function goBack() {
if (window.history.state?.back) {
router.back() // there was a previous screen in the application
} else {
router.push({ name: 'rooms' }) // the user came in directly: go to a sensible destination
}
}
RouterLink or router.push?
RouterLink or router.push?<RouterLink> |
router.push / replace |
|
|---|---|---|
| What it is | A link (<a href>) |
A call from code |
| When | The user chooses to go somewhere else | The navigation is a consequence of something: submitting a form, finishing an operation, an error, a timer |
| Opening in a new tab, copying the link | Yes | No |
| Accessibility | Announced as a link | Depends on the element that triggers the call |
Active classes, aria-current |
Yes | Not applicable |
| Examples in Colmena | Menus, "View spec sheet", breadcrumbs | After creating a booking, the "Back" button, filter changes |
The rule: if it is a link, use RouterLink. A <button @click="router.push(...)"> that only navigates is worse than a link: it cannot be opened in another tab and the screen reader announces it as an action. Use router.push when something else has to be done before (or after) navigating.
- Navigation is a promise: navigation failures
Navigating is not instantaneous: the router may have to download a lazy view and run guards (04-06). That is why push and replace return a promise that resolves when the navigation has finished and the new view is on screen:
await router.push({ name: 'dashboard-bookings' })
// The new screen has already been rendered here: you can move the focus, measure, etc.But a navigation may never actually take place. In that case the promise is not rejected: it resolves with a navigation failure. If everything goes well, it resolves with undefined. There are three types:
Type (NavigationFailureType) |
When it happens | Example |
|---|---|---|
duplicated |
You were already at exactly that destination | Clicking "My bookings" while on "My bookings" |
aborted |
A guard returned false |
The user cancels when leaving a form with changes (04-06) |
cancelled |
Another navigation started before this one finished | Clicking two links in quick succession while a view is downloading |
To tell them apart, you use isNavigationFailure:
import { useRouter, isNavigationFailure, NavigationFailureType } from 'vue-router'
const router = useRouter()
async function goToMyBookings() {
const failure = await router.push({ name: 'dashboard-bookings' })
if (isNavigationFailure(failure, NavigationFailureType.aborted)) {
console.info('The user has decided to stay on the screen')
} else if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
// already there: nothing to do
} else if (isNavigationFailure(failure)) {
console.warn('Could not navigate:', failure.to.fullPath)
}
}isNavigationFailure(value)checks whether it is a failure of any type; with the second argument, whether it is of that specific type.- The failure includes
toandfrom, the destination and origin locations. - The promise is rejected if a guard throws an unexpected error. That is not a "navigation failure" but a programming error, which you should catch with
try/catchor withrouter.onError. - A redirect (a guard that sends you to another route) is not a failure: the navigation ends at the new destination, and
router.currentRoute.value.redirectedFromindicates where it came from.
In most navigations there is no need to check anything. Do it when the code after the await assumes that the navigation has happened.
- Query parameters: reading
route.query
route.queryThe query (query string) is the part of the URL after the ?: key=value pairs separated by &. Unlike route params, it is not part of the pattern: /rooms, /rooms?floor=2 and /rooms?floor=2&sort=price-asc match the same route. That is why it is the natural place for a screen's options: filters, sort order, page, tab, search terms.
Route params (/rooms/:id) |
Query parameters (?floor=2) |
|
|---|---|---|
| Part of the pattern | Yes: without them, the route does not match | No: they are optional |
| They identify | Which resource is being viewed | How it is being viewed |
| Examples in Colmena | The room's id, the form's roomId |
The catalogue's filters, the proposed attendees |
| Read from | route.params |
route.query |
Vue Router parses the query and delivers it in route.query:
| URL | route.query |
|---|---|
/rooms |
{} |
/rooms?floor=2 |
{ floor: '2' } |
/rooms?floor=2&sort=price-asc |
{ floor: '2', sort: 'price-asc' } |
/rooms?equipment=projector&equipment=whiteboard |
{ equipment: ['projector', 'whiteboard'] } |
/rooms?q |
{ q: null } |
/rooms?q=n%C3%A9ctar%20room |
{ q: 'néctar room' } (already decoded) |
The most important thing in this table: everything arrives as a string (or null, or an array if the key is repeated). '2' is not 2, and the user can type anything into the address bar: ?floor=lots. Before using the query, you have to convert and validate it.
- Writing the query and converting types
To change the query, you navigate with query:
router.replace({ query: { floor: 2, sort: 'price-asc' } })
// → /rooms?floor=2&sort=price-asc (numbers are converted to text)When writing, a key whose value is undefined does not appear in the URL; with null, it appears without a value (?q). The usual practice is to omit the default values: if the default sort order is 'none', the URL does not need to say ?sort=none. That way URLs stay short, and a URL without a query is equivalent to "everything at its default".
For reading, the robust pattern is a function that, given the query, always returns valid values of the right type, falling back on the default value whenever anything unexpected turns up:
// If the key is repeated (?floor=1&floor=2), we keep the first value
function firstValue(value) {
return Array.isArray(value) ? value[0] : value
}
// An integer within a range, or the default value
function readInteger(value, min, max, fallback) {
const number = Number(firstValue(value))
return Number.isInteger(number) && number >= min && number <= max ? number : fallback
}
readInteger('2', 1, 3, null) // 2
readInteger('lots', 1, 3, null) // null
readInteger(['1', '2'], 1, 3, null) // 1
readInteger(undefined, 1, 3, null) // nullThat way, a tampered-with URL never breaks the screen: in the worst case, the invalid parameter is ignored.
- Case study: navigating from code and filters in the URL
9.1 "Book" goes straight to the form
In 04-02, clicking "Book" on a card showed a notice with a "Complete the booking" link, and in 04-03 we lost the attendees along the way. Now the button will navigate directly, with the attendees in the query: /book/nectar?attendees=4.
In the script of RoomsView.vue, add the router and replace bookingReady and prepareBooking:
import { useRoute, useRouter } from 'vue-router'
const route = useRoute() // we will use it for the filters (section 9.4)
const router = useRouter()
// Book: go to the form with the room in the route and the attendees in the query
function prepareBooking({ roomId, attendees }) {
router.push({
name: 'book',
params: { roomId },
query: { attendees: Math.max(1, attendees) }
})
}Delete the v-if="bookingReady" paragraph from the template. prepareBooking's signature does not change, so the three catalogue views and the panel's "Book this room" button keep working without being touched. It is a clear case for push: the button is not a simple link, because the attendees come from the card's internal state.
For BookingView to receive the attendees as a numeric prop, the route switches to using props in function mode (we saw it in 04-03). In src/router/index.js:
// Above const routes
function bookingProps(route) {
const attendees = Number(route.query.attendees)
return {
roomId: route.params.roomId,
attendees: Number.isInteger(attendees) && attendees > 0 ? attendees : 1
}
}
// The book route
{
path: '/book/:roomId([a-z-]+)',
name: 'book',
component: () => import('@/views/BookingView.vue'),
props: bookingProps
},And in BookingView.vue:
const { roomId, attendees } = defineProps({
roomId: { type: String, required: true },
attendees: { type: Number, default: 1 }
})The conversion and validation stay in a single place, the props function; the view receives a correct number or the default value, and it still knows nothing about the URL.
9.2 After creating the booking, on to "My bookings"
When the user creates a booking, the natural thing is to take them to their list and confirm that it has been saved. In BookingView.vue:
import { useRouter } from 'vue-router'
const router = useRouter()
async function createBooking(booking) {
recordBooking(booking)
bookingForm.value.reset()
await router.push({ name: 'dashboard-bookings', query: { new: booking.id } })
}The booking's id travels in the query (/dashboard/bookings?new=...) so that the list knows which one has just been created. In DashboardBookingsView.vue:
import { useRoute, useRouter } from 'vue-router'
import BaseButton from '@/components/base/BaseButton.vue'
const route = useRoute()
const router = useRouter()
const newBookingId = computed(() => route.query.new ?? null)
const newBooking = computed(() => bookings.value.find((b) => b.id === newBookingId.value))
function closeNotice() {
router.replace({ query: {} }) // removes ?new from the URL without adding a history entry
}<!-- DashboardBookingsView.vue, below the <h2> -->
<div v-if="newBooking" class="note new-booking-notice" role="status">
<p>
Booking created: {{ roomNameById(newBooking.roomId) }} on {{ newBooking.date }}
from {{ newBooking.startTime }} to {{ newBooking.endTime }}.
</p>
<BaseButton variant="secondary" @click="closeNotice">Close</BaseButton>
</div>
<!-- and in each booking's <li>, to highlight the new one -->
<li
v-for="booking in sortedBookings"
:key="booking.id"
:class="{ 'booking-list__new': booking.id === newBookingId }"
>.booking-list__new {
outline: 3px solid var(--color-honey);
}
.new-booking-notice {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}- Why in the query? Because the list is another screen: the data has to reach it somehow, and the URL is a visible channel that is easy to debug. If the user reloads,
newBookingwill not be found (the bookings live in memory) and the notice simply will not appear. closeNoticeusesreplace: closing a notice is not a new screen that you should be able to go back to.- There is an alternative:
router.pushaccepts astateoption that stores data inhistory.statewithout it appearing in the URL. It is neither reactive nor visible, so for something this simple we prefer the query.
9.3 A "Back" button on the spec sheet
On a room's spec sheet, the "← Catalogue" link always leads to /rooms without filters. Once we have put the filters in the URL (section 9.4), what the user expects when going back is their search. In RoomDetailView.vue:
import { useRouter } from 'vue-router'
const router = useRouter()
function goBack() {
if (window.history.state?.back) {
router.back()
} else {
router.push({ name: 'rooms' })
}
}<!-- Replaces <p><RouterLink :to="{ name: 'rooms' }">← Catalogue</RouterLink></p> -->
<BaseButton variant="secondary" @click="goBack">← Back</BaseButton>Here a button is correct: "going back" is an action on the history, not a link to a fixed destination.
9.4 The catalogue's filters in the URL
Today, RoomsView's filters are local refs. You saw this in 04-02: when you leave the catalogue and come back, they are lost; nor do they survive a reload or can they be shared. We are going to make the URL the source of truth: /rooms?floor=2&capacity=4&equipment=projector&sort=price-asc&q=nectar.
| Filter (variable) | Key in the URL | Type | Default value (does not appear in the URL) | Validation |
|---|---|---|---|---|
floorFilter |
floor |
a number or null |
null (all) |
An integer from 1 to 3 |
minCapacity |
capacity |
a number | 1 |
An integer from 1 to 100 |
requiredEquipment |
equipment |
text | '' |
— |
sort |
sort |
text | 'none' |
none, price-asc or price-desc |
search |
q |
text | '' |
— |
The idea is to replace each ref with a writable computed (02-05): its get reads from the URL and its set writes to the URL. Since they have the same names and are used in the same way (.value), nothing else in RoomsView has to change: not visibleRooms, not the watch that reloads the catalogue when floorFilter changes, and not RoomFilters' v-models.
In the script of RoomsView.vue, delete the ref declarations for floorFilter, minCapacity, requiredEquipment, sort and search, and add in their place (before the catalogue's watch, which uses floorFilter):
// --- Filters: the URL is the source of truth ---
const DEFAULT_VALUES = { floor: null, capacity: 1, equipment: '', sort: 'none', q: '' }
const VALID_SORTS = ['none', 'price-asc', 'price-desc']
function firstValue(value) {
return Array.isArray(value) ? value[0] : value
}
function readInteger(value, min, max, fallback) {
const number = Number(firstValue(value))
return Number.isInteger(number) && number >= min && number <= max ? number : fallback
}
// URL → filters: always valid values of the right type
const urlFilters = computed(() => {
const query = route.query
const sort = firstValue(query.sort)
return {
floor: readInteger(query.floor, 1, 3, null),
capacity: readInteger(query.capacity, 1, 100, 1),
equipment: firstValue(query.equipment) ?? '',
sort: VALID_SORTS.includes(sort) ? sort : 'none',
q: firstValue(query.q) ?? ''
}
})
// Filters → URL: only those that differ from the default value
function applyFilters(changes) {
const next = { ...urlFilters.value, ...changes }
const query = {}
for (const [key, value] of Object.entries(next)) {
if (value !== DEFAULT_VALUES[key]) {
query[key] = String(value)
}
}
return router.replace({ query })
}
// One writable computed per filter, with the same name as the old ref
function filterInUrl(key) {
return computed({
get: () => urlFilters.value[key],
set: (value) => applyFilters({ [key]: value })
})
}
const floorFilter = filterInUrl('floor')
const minCapacity = filterInUrl('capacity')
const requiredEquipment = filterInUrl('equipment')
const sort = filterInUrl('sort')
const search = filterInUrl('q')And change clearFilters, which used to assign the filters one by one:
// A single navigation with all the changes (it keeps the floor, as before)
function clearFilters() {
applyFilters({ capacity: 1, equipment: '', sort: 'none', q: '' })
}Let's analyse the design:
urlFiltersis the only place that reads the URL. It converts and validates each key with the functions from section 8:?floor=9or?sort=weirdare ignored. Since it depends onroute.query, it is recalculated on every query change.applyFilters(changes)combines the current filters with the changes, omits the default values and navigates withreplace. The destination{ query }, with neithernamenorpath, is relative to the current route: the URL is still/rooms(or/catalog, if the user came in through the alias).filterInUrl(key)manufactures the writable computeds.RoomFiltersstill usesv-model:floor="floorFilter": when "2" is clicked, it assignsfloorFilter.value = 2, thesetnavigates,route.querychanges,urlFiltersis recalculated and thegetreturns2. The cycle always goes through the URL.clearFiltersmakes a single navigation. If it assigned the four computeds one after another, eachsetwould start fromurlFiltersbefore the previous navigation had finished (navigation is asynchronous) and eachreplacewould tread on the one before. The rule: if several filters change at once, do it in a single call.replaceand notpush, for the reasons seen in section 3: Back should leave the catalogue, not undo the filters one at a time. It is a design decision: there are applications (search engines, shops) that preferpushso that Back does undo the filters. What matters is choosing it deliberately.- Synchronisation in both directions. If the query changes by any other route (the user pastes a URL, or clicks Back after visiting a spec sheet), the computeds return the new values,
RoomFilters' buttons are marked on their own and thefloorFilterwatchreloads the catalogue. Since the destination is the same route,RoomsViewis reused and is not mounted again. - The search box only emits when Enter is pressed, so there is not one navigation per keystroke. If a filter emitted on every keystroke, it would be advisable to wait until the user stops typing before touching the URL.
9.5 Sharing the search
Now that the URL contains the complete search, sharing it is a matter of copying the address. Add a button to the catalogue, in RoomsView.vue:
const linkCopied = ref(false)
async function copyLink() {
await navigator.clipboard.writeText(window.location.href)
linkCopied.value = true
setTimeout(() => (linkCopied.value = false), 2000)
}<!-- Next to RoomFilters -->
<BaseButton variant="secondary" @click="copyLink">
{{ linkCopied ? 'Link copied' : 'Copy link to this search' }}
</BaseButton>If you ever need the address of a location without navigating to it (for example, to share "the rooms with a projector" from another screen), router.resolve calculates it:
const { href } = router.resolve({ name: 'rooms', query: { equipment: 'projector' } })
// href === '/rooms?equipment=projector' (with the application's base, if there is one)
const fullLink = new URL(href, window.location.origin).toString()9.6 Try it
- Booking directly. On the Néctar card, add 4 attendees and click "Book": you arrive at
/book/nectar?attendees=4with 4 attendees in the form. Change the URL to?attendees=abc: the form shows 1. - After booking. Complete and submit the booking: you arrive at
/dashboard/bookings?new=...with the notice and the booking highlighted. Click "Close": the query disappears. Click Back: you return to the (empty) form. - Filters in the URL. In the catalogue, choose floor 2 and "Cheapest first": the URL changes to
/rooms?floor=2&sort=price-asc. Reload: the filters are still there and the catalogue loads already filtered. - There and back. With those filters, click a room's name and then "← Back": you return to the catalogue with your filters. Now open the
/rooms/polenspec sheet in a new tab and click "← Back": since there is no previous screen, you go to/rooms. - A clean history. Change the filters ten times and click Back once: you leave the catalogue for the previous screen. Temporarily change
router.replacetorouter.pushinapplyFiltersand repeat to notice the difference. Putreplaceback. - A tampered-with URL. Type
/rooms?floor=9&capacity=-3&sort=weird: the catalogue is shown without filters and without errors. Type/rooms?q=polen: the search box shows "polen" and the list is filtered. - Sharing. Click "Copy link to this search" and paste the address into another window: the same search.
- Duplicated failure. Temporarily add the line
console.log(await router.push(route.fullPath))at the end ofcopyLinkand click the button: in the console you will see a navigation failure object (of typeduplicated), because you were already at that address. Remove it.
Common Mistakes and Tips
- Passing
paramswithpath. They are ignored. Usename+params. - Using
paramsfor data that is not in the route. Vue Router discards it. Options go inquery; large amounts of data, in the shared state (todayprovide, in module 5 a store). - Comparing the query without converting it (
route.query.floor === 2). It is always a string,nullor an array. Convert and validate it in a single place. - Trusting that the query is valid. The user can type anything. Any unexpected value must fall back on the default value, never break the screen.
- Using
pushfor states that change often, filling up the history. For filters, sort order or tabs,replaceis usually the right choice. - Firing off several navigations in a row that start from the same query: the last one treads on the previous ones. Group the changes into one navigation.
- Using
router.back()without checking that there is a previous screen in the application. Checkhistory.state.backand have an alternative destination. - Buttons that only navigate. If it is a link, use
RouterLink: it can be opened in another tab and it is announced correctly. - Tip: after navigating to a screen as a consequence of an action (creating a booking), announce the result with a
role="status"region, like the notice in "My bookings": screen reader users also need to know what has happened.
Exercises
Exercise 1. Add the catalogue view (currentView: grid, table or map) to the URL with the view key, so that /rooms?view=table opens the table directly. Validate the value against the keys of the views object, and do not show it in the URL when it is the grid.
Exercise 2. Add a small search box to AppHeader (a <form role="search"> with a text field) that, when submitted, takes the user to the catalogue with the search in the query (/rooms?q=...). If the user is already in the catalogue, it must keep the other filters; if the navigation turns out to be a failure of type duplicated (the same search), show "You are already viewing that search" in the console.
Exercise 3. Starting from a history that contains only /, the user does the following, in order: clicks the "Rooms" link; chooses floor 2 (filters with replace); clicks the name "Néctar Room"; clicks "Other rooms → Polen Room"; clicks "Book this room"; submits the form (push to "My bookings"); clicks "Close" on the notice (replace). Write down what the history looks like and where each click of Back leads from there.
Solutions
Solution 1. currentView stops being a ref and becomes a writable computed:
// RoomsView.vue: replaces const currentView = ref('grid')
const currentView = computed({
get: () => {
const view = firstValue(route.query.view)
return Object.hasOwn(views, view) ? view : 'grid'
},
set: (view) => {
const { view: _previous, ...rest } = route.query
router.replace({ query: view === 'grid' ? rest : { ...rest, view } })
}
})The template (currentView === key, @click="currentView = key", views[currentView].component) does not change. Notice that the set does not go through applyFilters (which only knows about the five filters) and keeps the rest of the query with ...rest. applyFilters, on the other hand, builds a new query with only the filters and would delete view; for the two to coexist, start applyFilters with const query = route.query.view ? { view: route.query.view } : {}. Object.hasOwn avoids accepting inherited keys such as toString.
Solution 2.
<!-- AppHeader.vue -->
<script setup>
import { ref } from 'vue' // it was already imported
import { useRoute, useRouter, isNavigationFailure, NavigationFailureType } from 'vue-router'
const route = useRoute()
const router = useRouter()
const searchText = ref('')
async function runSearch() {
const q = searchText.value.trim()
// In the catalogue, keep the other filters; from another screen, start from scratch
const baseQuery = route.name === 'rooms' ? route.query : {}
const query = { ...baseQuery }
if (q) query.q = q
else delete query.q
const failure = await router.push({ name: 'rooms', query })
if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
console.info('You are already viewing that search')
}
}
</script>
<template>
<!-- inside the header -->
<form role="search" class="header__search" @submit.prevent="runSearch">
<label for="room-search" class="visually-hidden">Search rooms</label>
<input id="room-search" v-model="searchText" type="search" placeholder="Search rooms…" />
</form>
</template>Here push is appropriate: searching from the header means going to another screen, and Back should return the user to the previous one. The visually-hidden class (hidden visually but readable by screen readers) would have to be defined in the global styles; you could also use aria-label on the <input>.
Solution 3. The history entries, from oldest to most recent:
//rooms?floor=2: the link added/roomsand the filter replaced it./rooms/nectar/rooms/polen/book/polen?attendees=1/dashboard/bookings: thepushadded/dashboard/bookings?new=...and "Close" replaced it with the version without a query.
Clicking Back from entry 6: Polen's form (empty, because the view is mounted again), Polen's spec sheet, Néctar's spec sheet, the catalogue with floor 2 and, finally, the home page.
Conclusion
With useRouter() you have the router in your code: router.push navigates by adding an entry to the history and accepts strings or objects with path, name + params, query and hash; router.replace replaces the current entry, and go, back and forward move through the history (checking history.state.back before "going back"). Use RouterLink for links, and programmatic navigation when navigating is a consequence of another action. Each navigation returns a promise that resolves when it has finished, or with a failure (aborted, cancelled or duplicated) that is detected with isNavigationFailure. The query stores a screen's options in the URL; everything arrives as a string, so it is converted and validated in a single place, and default values are omitted. In Colmena, the "Book" button takes the user to the form with the attendees in the query (converted in the bookingProps function), creating a booking leads to /dashboard/bookings?new=... with a notice, the spec sheet has a "Back" button and the catalogue's filters live in the URL thanks to the writable computeds from filterInUrl: they survive reloads, can be shared with a link and are recovered when coming back from a spec sheet.
But anyone can navigate anywhere. A visitor without a session can open /dashboard or /book/nectar, a member can see the whole centre's invoices, and a user who has filled in half a form loses it without warning if they click a menu link. We need to be able to intervene in navigations: to allow them, cancel them or divert them. That is the job of Navigation Guards.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
