运行时动态添加路由
发布于 3 年前 作者 banyungong 1179 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

在用vue做业务系统的时候,因为业务系统的菜单、表格是动态配置的,感觉在登录的时候就把菜单和表格的各种操作读取然后用 addRoutes 做动态路由。我想在需要的时候,才增加动态路由。我实现了一下,下过是对了,但是不知道我的操作是否在合理的。请大家指教:
// 获取动态路由数组
const addDynamicsRoutes = () => {
const dynamicsRoutes = store.getters[‘runtimeroute/getRoutes’]
// 添加动态路由
dynamicsRoutes.forEach(element => {
insertDynamicsRoutes(element)
})
const allRoutes = router.options.routes
// 清空路由
router.matcher = new VueRouter({
routes: []
}).matcher

// 更新路由
router.options.routes = allRoutes
router.addRoutes(allRoutes)
}

// 递归写路由数组
function insertDynamicsRoutes (dynamicsRoute) {
const routes = router.options.routes
for (let i = 0; i < routes.length; i++) {
if (routes[i].name === dynamicsRoute.pName) {
const index = routes[i].children.findIndex(
t => t.name === dynamicsRoute.name
)
if (index === -1) {
const newRoute = {
path: dynamicsRoute.path,
name: dynamicsRoute.name,
component: require(@/${dynamicsRoute.componentUrl}).default,
meta: dynamicsRoute.meta
}
routes[i].children.push(newRoute)
}
break
} else if (routes.children) {
insertDynamicsRoutes(routes.children)
}
}
}

效果是实现了,关键是:
// 清空路由
router.matcher = new VueRouter({
routes: []
}).matcher
// 更新路由
router.options.routes = allRoutes
router.addRoutes(allRoutes)
这种操作是否合理?谢谢大家

回到顶部