Reputation: 4606
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.
Upvotes: 2
Views: 15503
Reputation: 22393
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
Upvotes: 2