ruoyi 替换默认首页 替换redirect 使用后台查询的菜单数据替换首页
本人使用的ruoyi 版本 为 4.8.2
接触ruoyi的过程中发现他有一个默认的首页,然而在使用的过程中,每个用户权限不一致。就会产生每个用户需要访问不同首页的需求。 下面咱们实现一下这个需求
- 编写一个获取首页路径的函数
function checkFirstCharacter(str, char) { //检查首位字节
return str.charAt(0) === char;
}
export function getMainPath(list , path) {
if (list?.length){
if (list[0].children){
return getMainPath(list[0].children , checkFirstCharacter(list[0].path , '/') ? list[0].path : '/'+ list[0].path );
}else {
console.log('===',path);
console.log('===',path? path +'/' + list[0].path : list[0].path);
return path? path +'/' + list[0].path : list[0].path
}
}
}
该函数的规则是 获取路由的最上方的第一个路由 如下方数据 会最终生成的路径为 /tool/build
[
{
"name": "Tool",
"path": "/tool",
"children": [
{
"name": "Build",
"path": "build",
"hidden": false,
"meta": {
"title": "表单构建",
"icon": "build",
"noCache": false,
"link": null
}
},
{
"name": "Gen",
"path": "gen",
"hidden": false,
"meta": {
"title": "代码生成",
"icon": "code",
"noCache": false,
"link": null
}
}
]
},
{
"name": "System",
"path": "/system",
"children": [
{
"name": "User",
"path": "user",
"hidden": false,
"meta": {
"title": "用户管理",
"icon": "user",
"noCache": false,
"link": null
}
}
]
}
]
- 第二步 删除原有首页
- 更改 src\permission.js 文件
代码如下
store.dispatch('GetInfo').then(() => {
isRelogin.show = false
store.dispatch('GenerateRoutes').then(accessRoutes => {
let path = getMainPath(accessRoutes) ; //首页
router.addRoutes([{ //更改路由
path: '/',
redirect: path
},
{
path: '/index',
redirect: path
}
])
router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
}).catch(err => {
store.dispatch('LogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})