commin.js
getPathList(menuList){
if(!menuList?.length) return [];
const pathList = menuList.flatMap(item=>{
const {highestRoleMenuVos,path} = item;
if(highestRoleMenuVos.length) return highestRoleMenuVos.map(menuItem=>menuItem.path);
return path;
})
return pathList;
}
main.js
router.beforeEach(async (to, from, next) => {
const role = common.getCookie("supply_token");
let menuList = store.state.menuList;
if (role) {
// 登录状态
if (to.path == "/login") {
next("/");
} else if(to.path == '/404'){
next();
}else {
// 查看是否存在动态menu等用户信息 不存在则获取动态菜单数据
console.log(menuList, typeof menuList);
if (menuList.length == 0) {
menuList = await store.dispatch("getMenuPermission");
const pathList = common.getPathList(menuList);
if (!pathList.includes(to.path)) {
next({ path: '/404' });
} else {
next({ ...to, replace: true });
}
} else {
const pathList = common.getPathList(menuList);
if (!pathList.includes(to.path)) { next({ path: '/404' }) } else {
next();
};
}
}
} else {
// 当前用户 未登录
if (to.path == "/login") {
next();
} else {
next("/login");
}
}
});
flatMap的案例
// 只会将 flatMap 中的函数返回的数组 “压平” 一层
const arr = [1, 2, 3].flatMap((x) => [[x * 2]]);
console.log(arr, "arr");
const datayin = [
{
code: 1001,
name: "zs",
age: 12,
address: "重庆",
mark: "",
sourceCodeList: [
{ checked: false, num: 0, mark: "主导打包" },
{ checked: true, num: 1, mark: "333" },
],
},
{
code: 1002,
name: "ls",
age: 15,
address: "武汉",
sourceCodeList: [
{ checked: false, num: null, mark: "1111" },
{ checked: true, num: 1, mark: "111" },
],
},
{
code: 1003,
name: "ww",
age: 15,
address: "深圳",
sourceCodeList: [{ checked: false, num: 11, mark: "" }],
},
];
const stockRegisterDetailList2 = datayin.flatMap(
({ sourceCodeList, ...parent }) => {
if (sourceCodeList.length) {
return sourceCodeList.map((v) => ({ ...v, ...parent }));
}
}
);
console.log(stockRegisterDetailList2, "stockRegisterDetailList2");
菜单权限返回值【如果是一菜单里有二级菜单的话,那其实一级菜单没有路由的【只是展示】,如果只有一级菜单那就是路由】
1.如果里面的highestRoleMenuVos长度大于0,说明有二级菜单遍历返回二级菜单的所有【path】
2.如果里面的highestRoleMenuVos长度等于0,直接返回解构出来的【path】
3.最后就会将一级菜单与二级菜单的path组合到一个数组返回出去
function getFlat() {
if (routesList.length == 0) return [];
const pathList = routesList.flatMap((item) => {
const { path, highestRoleMenuVos } = item;
console.log(path, "item");
if (highestRoleMenuVos.length) {
return highestRoleMenuVos.map((v) => v.path);
}
return path;
});
return pathList;
}
console.log(getFlat());