1.pinia中的处理后端返回的路由信息格式和存储
async getMenuInfo(router) {
const useMenusStore = menusStore();
//向Menus push数据
let res = await getMenus();
if (res.status === 'ok') {
useMenusStore.pushMenus({
resPath: '',
resName: '',
icon: '',
id: '',
children: res.data,
});
let isLogin = getCookie('nmp_username');
// 动态添加外链路由配置
let routerList = formatRoute(res.data);
routerList.forEach((item) => {
//router是从 router/index传入的router对象
router.addRoute(item);
});
}
return true;
},
//根据自己项目需求 将后端返回的路由数据配置为 路由需要的格式
const formatRoute = (resRouterList) => {
let oneList = getOneArr(JSON.parse(JSON.stringify(resRouterList)));
let isFrameList = oneList.filter((item) => item.is_frame === 1);
let arr = [];
isFrameList.forEach((item) => {
if (item.parent === 'index') {
item.path = '/' + item.parent + '/' + item.id;
arr.push({
path: item.path,
component: Home,
redirect: item.path,
meta: {
title: item.name,
tagShow: false,
},
children: [
{
path: item.path,
name: item.parent + item.id,
meta: {
title: item.name,
},
component: () => import('@/views/inline/inline.vue'),
},
],
});
} else {
let outPath = getOnePath(item, oneList);
item.path = outPath + '/' + item.id;
arr.push({
path: outPath,
component: Home,
redirect: item.path,
meta: {
title: item.name,
tagShow: false,
},
children: [
{
path: item.path,
name: item.parent + item.id,
meta: {
title: item.name,
},
component: () => import('@/views/inline/inline.vue'),
},
],
});
}
});
return arr;
};
2.router路由表中导航守卫
防止刷新页面丢失路由菜单,我这里用pinia里的hasMenus 来判断。但是设置hasMenus为true时,不要在pinia仓库修改。之后next要写为next({ ...to, replace: true }); 否则空白页
router.beforeEach(async (to, from, next) => {
// 获取菜单
// 判断登录后 再获取 登陆后的菜单
let isLogin = getCookie('nmp_username');
const userInfoStore = userStore();
// if (isLogin) {
// } else {
// }
if (to.path === '/login' || to.path === '/menhu' || to.path === '/') {
!userInfoStore.hasMenus ? await userInfoStore.getMenuInfo(router) : '';
next();
} else {
if (isLogin) {
//存用户信息
await userInfoStore.setUserInfo();
if (!userInfoStore.hasMenus) {
await userInfoStore.getMenuInfo(router);
userInfoStore.hasMenus = true;
next({ ...to, replace: true });
} else {
next();
}
} else {
!userInfoStore.hasMenus
? await userInfoStore.getMenuInfo(router)
: '';
next('/login');
}
}
});