我正在使用 Vue.js 和 vue-router,我正在尝试通过点击事件进行导航。
根据 vue-router documentation我应该使用 router.push(name)
API 函数。
问题是路由器在 App
根组件中初始化,我想从 App
子组件之一导航。
有没有办法从 this.$root
或类似的东西中获取路由器实例?
最佳答案
如 vue-router documentation 中所述,每个组件都被注入(inject)了 $router
和 $route
对象,使它们可以通过 this.$router
和 this.$ 访问组件内部的路由
。
如果你想从你的组件 javascript 代码导航,你只需要做:
this.$router.push({path: 'thepath'});
如果你想从你的模板导航,你可以使用:
<router-link :to="{path: 'thepath'}">The link</router-link>
vue-router repository 上有使用示例.
关于javascript - 视觉 : Getting the router instance in children components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41648785/