需求:vue前后端分离的项目中,需要动态加载所有的菜单项,我们无法在router.js里提前注册路由信息。
解决: 需要我们按需注册路由(即运行时注册)
步骤(1)后端传来的component一般都是字符串,我们需将其格式化成对象,然后按需注册。
export const formatRoutes = (routes) => {
let fmRoutes = [];
routes.forEach(router => {
//批量定义数据 后端传来的menu对象里的属性
let {
path,
component,
name,
meta,
iconCls,
children
} = router;
//递归子菜单
if(children && children instanceof Array){
children = formatRoutes(children)
}
let fmRouter = {
//path 路径 name 组件的名字
path: path,
name: name,
iconCls: iconCls,
meta: meta,
//children是子菜单项
children: children,
//按需加载
component(resolve) {
if (component.startsWith("Home")) {
//第一个参数就是组件里的位置
require(['../views/' + component + '.vue'], resolve);
} else if (component.startsWith("Emp")) {
require(['../views/emp/' + component + '.vue'], resolve);
} else if (component.startsWith("Per")) {
require(['../views/per/' + component + '.vue'], resolve);
} else if (component.startsWith("Sal")) {
require(['../views/sal/' + component + '.vue'], resolve);
} else if (component.startsWith("Sta")) {
require(['../views/sta/' + component + '.vue'], resolve);
} else if (component.startsWith("Sys")) {
require(['../views/sys/' + component + '.vue'], resolve);
}
}
}
fmRoutes.push(fmRouter)
})
return fmRoutes
}
(2)将返回的fmRoutes数组添加至路由中。
//data是后端的json字符串
let fmtRoutes = formatRoutes(data);
router.addRoutes(fmtRoutes);
此时我们已经将菜单项注册进路由了。