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

I'm using Vue.js and vue-router, I'm trying to navigate on a click event. According to vue-ro

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131829a4613008.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信