1、更具项目要求写导航守卫文件 permission.js
import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { bindWeChat } from "@/api/userCenter/personalCenter";
NProgress.configure({ showSpinner: false }); // NProgress Configuration
const whiteList = [
"/screen",
"/login",
"/register",
"/forget",
"/invite",
"/addTeam",
"/updatePassword",
"/bindAccount"
]; // 白名单
/**
* 路由拦截
* 权限验证
*/
let hasRoles = false;
router.beforeEach(async (to, from, next) => {
if (
window.location.href.indexOf("code") >= 0 &&
to.path === "/login" &&
from.path === "/login"
) {
let code = window.location.href.split("?")[1].split("&")[0];
code = code.substring(5);
store.state.wxCode = code;
store
.dispatch("user/login", {
account: code,
type: 3,
platform: 1
})
.then(() => {
router.push({ path: "/" });
});
}
// start progress bar
NProgress.start();
// set page title
document.title = await getPageTitle(to.meta.title);
// determine whether the user has logged in
const hasToken = getToken();
if (to.path === "/invite") {
next({ query: to.query });
}
if (hasToken) {
if (to.path === "/login") {
// if is logged in, redirect to the home page
next({ path: "/" });
NProgress.done();
}
if (to.path === "/updatePassword") {
next();
} else {
if (hasRoles) {
// 去往详情页的时候需要缓存组件,其他情况下不需要缓存 --->(需要提前加入缓存,因为第一次加入的数据是之前的)
// console.log('是否需要缓存:' + to.meta.keepAlive, to, to.meta.title)
if (to.meta.keepAlive) {
store.dispatch("permission/changeComponents", [
to.meta.keepAliveName
]);
} else if (!to.meta.keepAlive) {
store.dispatch("permission/changeComponents", []);
}
// console.log('加入的数组', store.state.permission.catchComponents)
next();
} else {
try {
if (from.path !== "/login" || to.path !== "/login") {
await store.dispatch("user/getInfo");
await store.dispatch("user/getConfig");
}
// get user info
// await store.dispatch("user/getInfo");
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const userMenu = await store.dispatch("user/menuLoad");
// console.log('userMenu',userMenu)
// generate accessible routes map based on roles
// const userRoutes = await store.dispatch('permission/generateRoutes', JSON.parse(menu))
// dynamically add accessible routes
const errorPage = { path: "*", redirect: "/404", hidden: true };
router.options.routes.push(...userMenu, errorPage);
// router.options.routes.push()
router.addRoutes([...userMenu, errorPage]);
// eslint-disable-next-line
hasRoles = true;
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
next(to.path, true);
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch("user/resetToken");
Message.error(error || "Has Error");
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next();
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`);
NProgress.done();
}
}
});
router.afterEach(() => {
// finish progress bar
NProgress.done();
});
2、在mian.js文件中引入
import '@/permission'