Cannot read property '_router' of undefined Vue js
12,755
You need to pass router
data to Vue component
import Vue from 'vue'
import App from './App.vue'
import Router from 'vue-router'
Vue.config.productionTip = false
export const changeRoute = new Vue();
Vue.use(Router) // should place it before new Vue()
// just example
const router = new Router({
routes: [
{
path: '/',
name: 'ToolDetail',
component: ToolDetail // place your component here
}
]
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
You can check more details in Getting Started document
Author by
Souvik Ghosh
Updated on June 25, 2022Comments
-
Souvik Ghosh almost 2 years
I am trying to redirect and pass data from one component to another using
vue-router
.In my main component I have a click link where I am calling a JavaScript function to do the routing.
<a href="javascript:void(0);" @click="switchComponent('ToolDetail')">click here</a> methods: { switchComponent(comp) { this.$router.push({name:comp}); },
As of now the routing itself is giving console error when the link is clicked.
Uncaught TypeError: Cannot read property '_router' of undefined
In my main.js I have already imported my router-
import Vue from 'vue' import App from './App.vue' import router from 'vue-router' Vue.config.productionTip = false export const changeRoute = new Vue(); new Vue({ render: h => h(App) }).$mount('#app') Vue.use(router)
Edit: Based on answer from @ittus, I did something like this-
In my main.js-
import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' Vue.use(VueRouter) Vue.config.productionTip = false new Vue({ render: h => h(App) }).$mount('#app')
In my
HomeContent.vue
-<template> ... .. <a href="javascript:void(0);" @click="switchComponent('ToolDetail')">click here</a> ... .. </template> <script> import ToolDetail from './ToolDetail.vue'; import VueRouter from 'vue-router'; ... .. methods: { switchComponent(comp) { const routes = [ { path: '/ToolDetail', component: ToolDetail, name: 'ToolDetail' } ] const router = new VueRouter({ routes }) router.push({name:'ToolDetail'}); }, ... .. </script>
Now, when I click the link nothing happens and no console error. Any help with this please? Let me know if I can provide more details.
-
dhaker almost 6 yearsAre you sure - HomeContent.vue exporting this in App.vue file ?, also make sure you are using
export
in HomeContent.vue correctly
-
-
Souvik Ghosh almost 6 yearsMy
App.vue
is the main component which will load other components. Also, I am importing thevue-rouer
in mymain.js
which has thenew Vue({..})
. How can importToolDetail
component and create theroutes: []
based on that? -
Souvik Ghosh almost 6 yearsUpdated the post based on your answer. Please check.
-
ittus almost 6 yearsYou need to set up routers in
main.js
component, not inHomeContent.vue
. Not that inmain.js
, you need to passrouter
:new Vue({ router, render: h => h(App) }).$mount('#app')