Reputation: 3811
I'm using Vue.js and vue-router, I'm trying to navigate on a click event.
According to vue-router documentation I should use the router.push(name)
API function.
The thing is that the router is initialized in the App
root component and I want to navigate from one of the App
component children.
Is there a way to grab the router insatnce from this.$root
or something similar?
Upvotes: 2
Views: 2795
Reputation: 144
Try this if you are using Vue.js 2 ( edited from @jeerbl answer )
<router-link :to="{path: 'thepath'}">The link</router-link>
Upvotes: 0
Reputation: 7867
As stated in the vue-router documentation, every component is being injected with $router
and $route
objects, making them accessible via this.$router
and this.$route
inside the component.
If you want to navigate from your component javascript code, you just need to do:
this.$router.push({path: 'thepath'});
If you want to navigate from your template, you can use:
<router-link :to="{path: 'thepath'}">The link</router-link>
There are examples of usage on the vue-router repository.
Upvotes: 4
Reputation: 2338
Yes, there is a very simple way -- it is automatically injected into all child components as this.$router
if you configured it per instructions in the official guide).
Upvotes: 3