VueRouter integration
##Introduction
vue-router received an upgrade as well to be compatible with Vue 3, and there are a small number of breaking changes.
The two most noteworthy ones are:
- How to create a
routerinstance - Usage of
<router-link>, where some props changed/were removed
In this chapter, we will be covering the first point, while we have a dedicated chapter about <router-link> in Part 2
Then, in Vue 2
In Vue 2, creating a router instance usually looks something like this:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: '/',
routes: [/* ... */],
})
const app = new Vue({
router,
// ..other options
})
- Register the plugin with
Vue.use() - call the
VueRouterconstructor - set the
mode - possibly set a
basepath - pass the
routesconfig. - pass new
routerinstance to theVueconstructor's options.
Now, in Vue 3
In Vue 3, the setup changed a bit:
import {createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
const app = createApp({ /* ... */ })
const router = createRouter({
history: createWebHistory('/')
routes: [/* ... */],
})
app.use(router)
- Create a
routerinstance withcreateRouter - create the
historywithcreateWebHistory()(or one of its siblings) baseise now the first argument of thehistoryfactory function.- add the
routerinstance to theappas a plugin viaapp.use()
Migrating the real app
Now, in a real app, the router config is often done in its own file, i.e. router.js, and then the router is exported and imported into main.js.
That's true for a default VueCLI setup and for our example app as well.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Todos from '../views/Todos.vue'
Vue.use(VueRouter)
const routes = [
// omitted
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
})
export default router
import Vue from 'vue'
import router from './router'
// omitted
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
Applying our changes to that router.js file, it now looks like this:
import { createRouter, createWebHistory } from 'vue-router'
import Todos from '../views/Todos.vue'
const routes = [
/* */
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
})
export default router
And in main.js, we now import the router and register it:
import { createApp } from 'vue'
import router from './router'
// rest of the code omitted
const app = createApp(App)
app.use(router)
app.mount('#app')
VueRouter Migration Guide
There are of course other changes in VueRouter v4 that may be affecting your app. All of those are covered in the official Migration guide in the dos for v4.
A small excerpt:
Read the full VueRouter v4 Migration guide here