0
votes

All the code is at https://github.com/shanegibney/vue-component-routes

Using Vue3.8.3, I am trying to use and to link to single page components. These components are registered in src/routes/index.js here is the file

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'

Vue.use(VueRouter)

export default new Router({
  routes: [{
    path: '/',
    name: 'Home',
    component: Home
  }, {
    path: '/about',
    name: 'About',
    component: About
  }]
})

That should set up the routes.

Then Home.vue component contains a menu which should link to these components.

Home.vue

<template>
  <div class="home">
  <b-navbar type="light" variant="light" toggleable="md">
    <b-navbar-toggle target="nav_collapse"></b-navbar-toggle>
    <b-collapse is-nav id="nav_collapse">
      <b-navbar-nav>
        <router-link to="/">Home</router-link>
        <router-link to="/about">About</router-link>
      </b-navbar-nav>
    </b-collapse>
  </b-navbar>
    <div>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>

<style>
</style>

Also the App.vue file looks like this,

<template>
  <div id="app">
    <div class="">
      I am app.vue
    </div>
    <Home />
  </div>
</template>

<script>
import Home from '@/components/Home.vue'
export default {
  name: 'app',
  components: {
    Home
  }
}
</script>

all this really does is calls the Home.vue component.

If the components are registered in src/routes/index.js should they be globally accessible?

Also after I installed routes using $npm install vue-router I created the directory routes inside src because it did not exist. Then I put index.js inside routes. Perhaps this is not correct.

Not sure if it is helpful but main.js looks like this,

import Vue from 'vue'
import '@babel/polyfill'
import 'mutationobserver-shim'
import VueRouter from 'vue-router'
import './plugins/bootstrap-vue'
import App from './App.vue'

Vue.use(VueRouter)
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

The error I get mentions a 'mismatch',

[Vue warn]: Error in render: "TypeError: Cannot read property 'matched' of undefined"

I presume this is something to do with the routes in index.js not matching with the "to" paths in router-link.

How can I ensure index.js in being included in the app?

Any help would be greatly appreciated.

Thanks,

1

1 Answers

1
votes

You forgot to inject your router in the Vue app:

import Vue from 'vue'
import '@babel/polyfill'
import 'mutationobserver-shim'
import VueRouter from 'vue-router'
import './plugins/bootstrap-vue'
import App from './App.vue'
import router from './router' // <= here

Vue.use(VueRouter)
Vue.config.productionTip = false

new Vue({
  router, // <= and here
  render: h => h(App),
}).$mount('#app')