vue-router如何动态(在某个页面下)添加子路由?
假设路由配置如下:
router.js
const router = new Router({
routes: [
{ path: '/401', component: () => import('@/views/errorPage/401'), hidden: true },
{ path: '/login', name: 'login', component: () => import('@/views/login/index'), hidden: true },
{
path: '',
component: Layout,
redirect: 'dashboard',
children: [
{ path: 'dashboard', name: 'dashboard', component: () => import('@/views/dashboard/index') },
{
path: 'project',
name: 'project',
component: () => import('@/views/project/index'), //在此页面动态添加子路由,即追加 children 属性
children: [
]
}
]
},
]
})
export default router
突然某一天,我希望为路由project
添加子路由(project-child-route1
、project-child-route2
)该怎么操作呢?
我希望在/views/project/index
页面上来(通过当前路由),希望只是在project
节点的children
属性下添加内容,伪代码如下:
this.$router.children.push([childRoute1, childRoute2]);
或者通过导入router.js
来导入也行,而不是得通过覆盖路由的方式添加,如下:
routes: [
{ path: '/401', component: () => import('@/views/errorPage/401'), hidden: true },
{ path: '/login', name: 'login', component: () => import('@/views/login/index'), hidden: true },
{
path: '',
component: Layout,
redirect: 'dashboard',
children: [
{ path: 'dashboard', name: 'dashboard', component: () => import('@/views/dashboard/index') },
{
path: 'project',
name: 'project',
component: () => import('@/views/project/index'), //在此页面动态添加子路由,即追加 children 属性
children: [
]
}
]
},
],
//注意,在下面追加了一份和上面差不多的配置(所以说是覆盖)
{
path: '',
component: Layout,
redirect: 'dashboard',
children: [
{ path: 'dashboard', name: 'dashboard', component: () => import('@/views/dashboard/index') },
{
path: 'project',
name: 'project',
component: () => import('@/views/project/index'), //在此页面动态添加子路由,即追加 children 属性
children: [
{ path: '/project-child-route1', component: () => import('@/views/project/project-child-route1'), hidden: true },
{ path: '/project-child-route2', component: () => import('@/views/project/project-child-route2'), hidden: true },
]
}
]
},
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现原理应该和vue权限控制动态路由生成是一样的,利用路由懒加载或字典映射等手段为路由匹配对应的实例组件,根据场景创建新路由列表并执行挂载。如果还有侧边菜单的话还要同步更新菜单列表缓存。