思路就是前端寫好全部的菜單信息,通過接口從後端拿相應權限。拿到之後使用全局守衛結合addRoute實現路由權限控制。
在日常開發中路由權限控制是經常遇到的,以下是我的部分代碼實現:
名詞解釋:
全局守衛:
全局路由守衛每次都判斷用戶是否已經登錄,沒有登錄則跳到登錄頁。已經登錄(已經取得後臺返回的用戶的權限信息(角色之類的)),則判斷當前要跳轉的路由,用戶是否有權限訪問(根據路由名稱到全部路由裏找到對應的路由)。沒有權限則跳到事先定義好的界面(403,404之類的)。
addRoute:
addRoutes
允許在應用初始化之後,動態的掛載路由。
實現:
第一步:
應用初始化的時候先掛載不需要權限控制的路由,比如登錄頁,404等錯誤頁。
// router.js 初始化界面
import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "../views/layout/Layout";
Vue.use(VueRouter);
const routes = [
{
path: "/login",
name: "login",
component: () => import("../views/login/login")
},
{
path: "/404",
name: "404",
component: () => import("../views/errorPage/404")
}
];
const router = new VueRouter({
mode: "history",
base: "/sdd/",
routes
});
export default router;
第二步:
全局路由守衛結合addRoute實現路由動態控制。
// permission.js 文件在main.js中直接引入
import router from "./router";
import NProgress from "nprogress";// 一個進度條控制組件
import "nprogress/nprogress.css";
import store from "./store";
import { generateMenu } from "./views/layout/components/utils/menu";
NProgress.configure({ showSpinner: false }); // 固定搭配
const whiteList = ["/login"]; // 白名單
router.beforeEach(async (to, from, next) => {
NProgress.start();
if (sessionStorage.token) {
if (to.path === "/login") {
next({ path: "/" });
NProgress.done();
} else {
// 獲取當前用戶信息
if (from.path === "/login" || !store.state.user.userInfo.username) {
const res = await store.dispatch("user/getUserInfo");
if (res.code !== 0) {
if (res.code !== 5002) {
sessionStorage.removeItem("token");
next({ path: "/login" });
NProgress.done();
}
} else {
// 獲取用戶權限
if (store.state.user.routes.length === 0) {
store
.dispatch("user/listMenus")
.then(res => {
// 路由遍歷爲樹的形式
const routes = generateMenu(res.data) || [];
store.dispatch("user/setRoutes", routes);
routes.push({
path: "*",
redirect: "/404"
});
router.addRoutes(routes); // 動態添加可訪問路由表
next({ ...to, replace: true }); // hack方法 確保addRoutes已完成
})
.catch(() => {
sessionStorage.removeItem("token");
next({ path: "/login" });
NProgress.done();
});
} else {
next();
}
}
} else {
next();
}
}
} else {
// 白名單上的path 直接next()
if (whiteList.includes(to.path)) {
next();
} else {
next({ path: "/login" });
NProgress.done();
}
}
});
router.afterEach(() => {
NProgress.done();
});
generateMenu 方法實現:
import Layout from "../../Layout";
const menuMap = {
// 首頁
home_page: {
path: "/",
icon: "Dashboard",
component: Layout
},
// 客戶端用戶
client_user_module: {
path: "/client-setting",
icon: "clientUser",
component: Layout
},
client_user_manager_submodule: {
path: "user",
icon: "clientUser",
component: () => import("../../../clientSetting/clientUser/clientUser")
},
client_user_template_submodule: {
path: "authority",
icon: "template",
component: () =>
import("../../../clientSetting/clientAuthority/clientAuthority")
},
client_user_announcement_submodule: {
path: "notice",
icon: "notice",
component: () =>
import("../../../clientSetting/clientSendNotice/clientSendNotice")
},
// 鏡像管控
image_manager_module: {
path: "/system-image",
icon: "SystemImage",
component: Layout
},
image_manager_submodule: {
path: "management",
icon: "SystemImage",
component: () =>
import("../../../systemImage/systemImageManagement/systemImageManagement")
},
// 終端管控
terminal_manager_module: {
path: "/terminal-management",
icon: "Terminal",
component: Layout
},
terminal_manager_submodule: {
path: "management",
icon: "Terminal",
// prettier-ignore
component: () =>
import("../../../terminalManagement/terminalManagement/terminalManagement")
},
firmware_upgrade_submodule: {
path: "firmware-upgrade",
icon: "Upgrade",
component: () =>
import("../../../terminalManagement/firmwareUpgrade/firmwareUpgrade")
},
// 資產統計
asset_manager_module: {
path: "/asset-statistics",
icon: "Asset",
component: Layout
},
asset_hardware_submodule: {
path: "hardware",
icon: "Hardware",
component: () => import("../../../assetStatistics/hardware/hardware")
},
// 審計管理
audit_manager_module: {
path: "/audit-management",
icon: "Audit",
component: Layout
},
system_log_submodule: {
path: "systemLog",
icon: "systemLog",
component: () => import("../../../auditManagement/systemLog/systemLog")
},
web_log_submodule: {
path: "webLog",
icon: "webLog",
component: () => import("../../../auditManagement/webLog/webLog")
},
illegality_connect_log_submodule: {
path: "illegalOutreachLog",
icon: "illegalLog",
component: () =>
import("../../../auditManagement/illegalOutreachLog/illegalOutreachLog")
},
device_safe_log_submodule: {
path: "deviceSecurityLog",
icon: "deviceLog",
component: () =>
import("../../../auditManagement/deviceSecurityLog/deviceSecurityLog")
},
alarm_log_submodule: {
path: "alarm-log",
icon: "Alarm",
component: () => import("../../../auditManagement/alarmLog/alarmLog")
},
asset_hardware_change_log_submodule: {
path: "hardware-log",
icon: "HardwareLog",
component: () => import("../../../auditManagement/hardwareLog/hardwareLog")
},
power_control_log_submodule: {
path: "power-log",
icon: "Power",
component: () => import("../../../auditManagement/powerLog/powerLog")
},
// 系統設置
system_config_module: {
path: "/system-setting",
icon: "Setting",
component: Layout
},
global_config_submodule: {
path: "param",
icon: "params",
component: () => import("../../../systemSetting/systemParam/systemParam")
},
sysuser_manager_submodule: {
path: "user",
icon: "systemUser",
component: () => import("../../../systemSetting/systemUser/systemUser")
},
sysrole_manager_submodule: {
path: "role",
icon: "systemRole",
component: () => import("../../../systemSetting/systemRole/systemRole")
},
data_clear_submodule: {
path: "dataClean",
icon: "dataClean",
component: () =>
import("../../../systemSetting/systemDataClean/systemDataClean")
},
resource_center_submodule: {
path: "resource-center",
icon: "ResourceCenter",
component: () =>
import("../../../systemSetting/resourceCenter/resourceCenter")
},
// 系統幫助
system_help: {
path: "/help",
icon: "Help",
component: Layout
},
system_help_about: {
path: "about",
icon: "About",
component: () => import("../../../help/about/about")
}
};
export function generateMenu(menu) {
// 兩級菜單
const travelMenu = menu => {
let routes = [];
for (let item of menu) {
let route = {};
route.name = item.moduleName;
route.path = menuMap[item.moduleId] && menuMap[item.moduleId].path;
route.component =
menuMap[item.moduleId] && menuMap[item.moduleId].component;
route.icon = menuMap[item.moduleId] && menuMap[item.moduleId].icon;
if (item.childModules && item.childModules.length > 0) {
route.children = travelMenu(item.childModules);
}
if (route.path && route.component) {
routes.push(route);
}
}
// 添加重定向
routes.forEach(item => {
if (item.path === "/") {
item.redirect = "/dashboard";
item.children = [
{
path: "dashboard",
component: () => import("../../../dashboard/dashboard"),
name: item.name
}
];
} else if (item.children) {
item.redirect = item.path + "/" + item.children[0].path;
}
});
return routes;
};
return travelMenu(menu);
}