在Vuejs中动态添加子路由

时间:2018-02-16 17:41:58

标签: vue.js lazy-loading vue-router dynamic-routing

根据this官方示例,我们可以在vuejs中添加嵌套/子路由。但我找不到任何关于动态添加这些子路由的方法的帮助/文档。例如,仅在访问父路由时添加子路由。

目前,Vue应用程序中的所有路由都是在我们创建路由器实例的地方定义的。有一个名为addRoutes的api,但我不知道如何使用它来添加应用程序的延迟加载功能。如果有人熟悉Angular2 + Module系统,那么就可以为该模块中的功能模块定义路由,甚至可以延迟加载它们。想知道是否可以用VueJs实现某些目标?

1 个答案:

答案 0 :(得分:1)

您可以使用$router.addRoutes重新添加路线,指定子项。

您需要通过在$route数组中搜索与当前$router.options.routes匹配的路由定义对象来获取当前路由定义(而不是$route.path对象)。然后向对象添加children路由定义数组,并将其传递给$router.addRoutes

created() {
  let { routes } = this.$router.options;
  let routeData = routes.find(r => r.path === this.$route.path);
  routeData.children = [
    { path: 'bar', component: Bar },
    { path: 'baz', component: Baz },      
  ];
  this.$router.addRoutes([routeData])
}

Here's an example fiddle of dynamically adding child routes in the creaked hook of a route's component definition.

相关问题