Navigation doesn't always happen by clicking a link. We often need to navigate after performing an action - like the automatic redirect system in NOVA LAB after completing a procedure.
The
useRouter() composable gives access to the router instance:1<script setup>
2import { useRouter } from 'vue-router'
3
4const router = useRouter()
5</script>Adds a new entry to the browser history (the back button will work):
1<script setup>
2import { useRouter } from 'vue-router'
3
4const router = useRouter()
5
6function navigateToSystem(id) {
7 // String path
8 router.push('/system/42')
9
10 // Named route with parameters
11 router.push({
12 name: 'system-detail',
13 params: { id: 42 }
14 })
15
16 // With query parameters
17 router.push({
18 path: '/systems',
19 query: { module: 'habitat', sort: 'priority' }
20 })
21}
22</script>Replaces the current entry in history (you can't go back with the back button):
1<script setup>
2import { useRouter } from 'vue-router'
3
4const router = useRouter()
5
6function afterLogin() {
7 // After login - replace login in history
8 router.replace({ name: 'dashboard' })
9}
10</script>Navigation in browser history:
1<script setup>
2import { useRouter } from 'vue-router'
3
4const router = useRouter()
5
6// Go back one step
7router.go(-1)
8router.back() // alias for go(-1)
9
10// Go forward
11router.go(1)
12router.forward() // alias for go(1)
13
14// Go back 3 steps
15router.go(-3)
16</script>A common pattern - navigation after completing an operation:
1<script setup>
2import { ref } from 'vue'
3import { useRouter } from 'vue-router'
4
5const router = useRouter()
6const form = ref({ name: '', status: '' })
7
8async function submitForm() {
9 try {
10 const result = await saveSystem(form.value)
11
12 // After saving - go to details
13 router.push({
14 name: 'system-detail',
15 params: { id: result.id }
16 })
17 } catch (error) {
18 console.error('Save error:', error)
19 }
20}
21
22function cancel() {
23 // Go back to the list
24 router.push({ name: 'systems-list' })
25}
26</script>
27
28<template>
29 <form @submit.prevent="submitForm">
30 <input v-model="form.name" placeholder="System name" />
31 <button type="submit">Save</button>
32 <button type="button" @click="cancel">Cancel</button>
33 </form>
34</template>These are two different composables:
useRoute() - information about the CURRENT route (params, query, path, name)useRouter() - router instance for NAVIGATION (push, replace, go)1<script setup>
2import { useRoute, useRouter } from 'vue-router'
3
4const route = useRoute() // read: route.params.id
5const router = useRouter() // navigate: router.push(...)
6</script>