Historical archive
Vue Router 4 Notes for Vue 3
A concise guide to Vue Router 4 installation, history modes, dynamic routes, Composition API helpers, navigation guards, and useLink().
Vue Router 4 retained most of the familiar API while changing how router instances and history modes are configured.
Installation
At the time of the original Vue 3 release, the prerelease package was installed with:
npm install vue-router@next
Modern projects should install the current vue-router release.
Create a router
- Use
createRouter(). - The old
modeoption is replaced byhistory. - Use
createWebHistory(),createWebHashHistory(), orcreateMemoryHistory(). - The old
baseoption moves into the history factory, such ascreateWebHistory('/base-directory').
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', component: Dashboard },
{ path: '/todos', component: Todos },
],
})
Add a route dynamically
router.addRoute({
path: '/about',
name: 'about',
component: () => import('./components/About.vue'),
})
Access the router
import { useRouter } from 'vue-router'
const router = useRouter()
React to route changes
import { useRoute } from 'vue-router'
const route = useRoute()
watch(
() => route.query,
query => {
console.log(query)
}
)
Composition API guards
onBeforeRouteLeave((to, from) => {
const answer = window.confirm(
'Are you sure you want to leave this page?'
)
if (!answer) {
return false
}
})
// onBeforeRouteUpdate(...)
useLink()
useLink() exposes the state and navigation behavior used internally by RouterLink:
const {
route,
href,
isActive,
isExactActive,
navigate,
} = useLink(props)