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?
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 .
如果您使用Vue.js 2(从@jeerbl回答编辑),请尝试此操作
<router-link :to="{path: 'thepath'}">The link</router-link>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.