1
votes

Trying to implement vue router. Getting the error:

Cannot read property 'forEach' of undefined
    at createRouterMatcher 

Vue Version: @vue/cli 4.5.9. I have two views/pages already formatted and ready to implement. My home page will be basically be the index.vue. Ive tried playing around with index.js and main.js but can't seem to get it to work.

src/main.js

import { createApp } from 'vue'
import { routes } from './router/index'
import { createRouter, createWebHistory } from 'vue-router'
require('dotenv').config();
import App from './App.vue'
import './index.css'

let app = createApp(App)
let router = createRouter({
  history: createWebHistory(),
  routes,
})

app.use(router)

app.mount('#app')

src/router/index.js

import Index from '../views/index.vue'
import About from '../views/about.vue'

const routes =  [
    {
        path: "/",
        name: "Index",
        component: Index
    },
    {
        path:"/about",
        name: "About",
        component: About
    }
]

export default routes;

src>App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>

export default {
  name: 'App',
}
</script>

Both my views index.vue & about.vue both have export default { name: 'pagename'} accordingly

1

1 Answers

0
votes

You're using a default export, which means routes is not a named export and shouldn't use brackets. This will fix the problem:

import routes from './router/index'  // no brackets

But I recommend doing all of the router setup in the router file and exporting the router instead of the routes:

router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import Index from '../views/index.vue'
import About from '../views/about.vue'

const routes =  [
    {
        path: "/",
        name: "Index",
        component: Index
    },
    {
        path:"/about",
        name: "About",
        component: About
    }
]

let router = createRouter({
  history: createWebHistory(),
  routes,
})

export default router;

main.js

import { createApp } from 'vue'
import router from './router/index'
require('dotenv').config();
import App from './App.vue'
import './index.css'

let app = createApp(App)
app.use(router)
app.mount('#app')