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 ponent and I want to navigate from one of the App
ponent children.
Is there a way to grab the router insatnce from this.$root
or something similar?
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 ponent and I want to navigate from one of the App
ponent children.
Is there a way to grab the router insatnce from this.$root
or something similar?
-
Well you have to define that child ponent in the routes, assign it path and name, and then you can do just
router.push('child-ponent')
. I'm not sure that I totally understand your issue, so better explanation would help a lot. – Belmin Bedak Commented Jan 14, 2017 at 11:43
3 Answers
Reset to default 4As stated in the vue-router documentation, every ponent is being injected with $router
and $route
objects, making them accessible via this.$router
and this.$route
inside the ponent.
If you want to navigate from your ponent 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.
Yes, there is a very simple way -- it is automatically injected into all child ponents as this.$router
if you configured it per instructions in the official guide).
Try this if you are using Vue.js 2 ( edited from @jeerbl answer )
<router-link :to="{path: 'thepath'}">The link</router-link>