为什么`router.addRoutes()` 添加的路由在 this.$router.options 看不到?

只能看到路由配置里配置的固定路由表.
而后端传过来的路由配置, 通过 router.addRoutes() 添加的路由, 却看不到.

我想要实现的需求是, 当前页面下, 获取当前路由路径, 动态将子路由添加进去.

阅读 14.4k
1 个回答

如果你指的是动态路由通过 this.$router.options 找不到,这是 vue-router 故意这么设计的,曾经有人和你一样以为这是 Bug 而提了 Issus(传送门:https://github.com/vuejs/vue-...)。

作者的回复是:

options is the object passed to the vuerouter constructor. It's not modified afterwards.

如果你非要这么做,可以这么做:

let newRoutes = []; // 要动态添加的路由

this.$router.addRoutes(newRoutes);
this.$router.options.routes = this.$router.options.routes.concat(newRoutes);

但不建议这么做,原帖下有作者的更进一步说明,真需要动态路由的话最好还是配合 vuex store 来做。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题