在Vuejs中动态添加子路由 [英] Dynamically add child routes in Vuejs

查看:42
本文介绍了在Vuejs中动态添加子路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to this official example, we have the ability to add nested/children routes in vuejs. But I cannot find any help/docs around a way to add these children routes dynamically. e.g only add child routes when Parent route is visited.

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

Currently all the routes in a Vue application are defined in a single place where we create Router instance. There is an api called addRoutes, but I don't know how to use that to add lazily loaded features of application along side their routes. If someone is familiar with Angular2+ Module system, that has this ability to define routes for the feature modules inside that module and even make them lazily loaded. Wondering if something could be achieved with VueJs?

推荐答案

您可以使用 $ router.addRoutes 重新添加路由,并指定子级.

You can use $router.addRoutes to re-add a route, specifying children.

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

You'll need to get the current route definition (as opposed to the $route object) by searching the $router.options.routes array for the route definition object that matches the current $route.path. Then add a children array of route definitions to the object and pass it to $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])
}

这是在 created 钩子中动态添加子路由的示例小提琴路线的组件定义.

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

这篇关于在Vuejs中动态添加子路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆