vue路由权限设计
路由创建
// src/router/index.js
import { createRouter, createWebHashHistory } from "vue-router";
import { constantRouterMap } from "@/config/router.config";
const router = createRouter({
history: createWebHashHistory(),
routes: constantRouterMap,
});
export default router;
创建本地路由表
- 页面路由:constantRouterMap
- 基础路由:constantRouterMap
import { constantRouterMap } from "@/config/router.config";
创建路由钩子
router.beforeEach((to, from, next) => {
NProgress.start(); // start progress bar
/* has token */
if (storage.getItem(STORAGE.TOKEN)) {
if (to.path === loginRoutePath) {
next({ path: defaultRoutePath });
NProgress.done();
} else {
// check login user.roles is null
if (store.state.user.roles.length === 0) {
// request login userInfo
store
.dispatch("user/GetInfo")
.then(res => {
console.info("获取用户信息", res);
const roles = res.result && res.result.role;
// generate dynamic router
store.dispatch("permission/GenerateRoutes", { roles }).then(() => {
// 根据roles权限生成可访问的路由表
// 动态添加可访问路由表
// VueRouter@3.5.0+ New API
store.state.permission.addRouters.forEach(r => {
router.addRoute(r);
});
debugger;
// 请求带有 redirect 重定向时,登录自动重定向到该地址
const redirect = decodeURIComponent(from.query.redirect || to.path);
if (to.path === redirect) {
// set the replace: true so the navigation will not leave a history record
next({ ...to, replace: true });
} else {
// 跳转到目的路由
next({ path: redirect });
}
});
})
.catch(err => {
console.error(err);
debugger;
notification("请求用户信息失败,请重试");
// 失败时,获取用户信息失败时,调用登出,来清空历史保留信息
store.dispatch("user/Logout").then(() => {
next({ path: loginRoutePath, query: { redirect: to.fullPath } });
});
});
} else {
next();
}
}
} else if (allowList.includes(to.name)) {
// 在免登录名单,直接进入
next();
NProgress.done(); // finish progress bar
} else {
next({ path: loginRoutePath, query: { redirect: to.fullPath } });
NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
}
});
router.afterEach(() => {
NProgress.done(); // finish progress bar
});
前后端同步路由表
所有路由的创建都通过菜单来做,禁止私自修改本地缓存的路由信息;
要点
- 每次发送路由变更请求后都要清楚本地中这次请求对应的参数信息
- 所有的路由节点的name是唯一的