Search code examples
javascriptvue.jsvue-routervuejs3vue-router4

Vue.js 3 - Why is importing vue-router not working in this case?


I have the following files

router.js

import VueRouter from 'vue-router'

export const router = VueRouter({
routes: [
     {
      ...
     }
 ]
})

main.js

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
...
import { router } from './router'
app.use(router)
...
app.mount('#app')

However when doing this I get the following error Uncaught TypeError: this is undefined - vue-router.esm.js:2828 it seems to be an error inside vue-router library since the error occures at line 2828.

This happens by just trying to import vue-router without trying to use it anywhere else in the app, I also use vuex and import export/import store the same way and it works.

My guess is that I'm importing vue-router wrong because the docs don't use {createApp} in the example. Am I importing it wrong, or is there some other reason it doesn't work ?


Solution

  • First make sure the you've installed the vue router 4 using :

    npm install vue-router@next
    

    then import createRouter to create router instance:

     import { createRouter,createWebHistory} from 'vue-router'
    
    const router = createRouter({
      history: createWebHistory(process.env.BASE_URL),
      routes: [
         {
          ...
         }
     ]
    })