最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue: Getting the router instance in children components - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question edited Jan 16, 2017 at 0:34 jeerbl 7,9175 gold badges26 silver badges39 bronze badges asked Jan 14, 2017 at 10:07 ShikloshiShikloshi 3,8319 gold badges39 silver badges61 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 4

As 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>
发布评论

评论列表(0)

  1. 暂无评论