路由守卫就是路由跳转过程中的一些 钩子函数,在路由跳转的时候,做一些判断或其它的操作。 类似于组件生命周期钩子函数 。
路由守卫的分类:
1.全局路由守卫
- beforeEach(to, from, next) 全局前置守卫,路由跳转前触发
- beforeResolve(to, from, next) 全局解析守卫 在所有组件内守卫和异步路由组件被解析之后触发
- afterEach(to, from) 全局后置守卫,路由跳转完成后触发
2.路由独享守卫
beforeEnter(to,from,next) 路由对象单个路由配置 ,单个路由进入前触发
3.组件路由守卫
beforeRouteEnter(to,from,next) 在组件生命周期beforeCreate阶段触发事件
beforeRouteUpdadte(to,from,next) 当前路由改变时触发事件
beforeRouteLeave(to,from,next) 导航离开组件的对应路由时触发事件
路由参数:
to: 即将要进入的目标路由对象
from: 即将要离开的路由对象
next(Function):是否可以进入某个具体路由,或者是某个具体路由的路径
router.beforeEach((to, from, next) => {
console.log("routemgr to", to.path);
if ("这里判断是不是开发环境") {
next();
} else {
if (to.path == "/login") {
//登录页面
session.set("isOpen", "ok");
next();
} else if ("这里判断如不是生产环境下录页面需要判断权限") {
//非生产环境下
next();
} else {
console.log("routemgr user", lu.userinfo);
if (gadget.isEmptyObject(lu.userinfo)) {
//首次打开页面的时候,不需要弹出错误页面提示,直接跳转至登录页面即可
let ret = session.get("isOpen");
if (ret == "ok") {
//vuex用户信息判断,如果不存在,则重新登录
MessageBox.alert("用户未登录,需要重新登录.", "错误", {
confirmButtonText: "确定",
type: "error",
}).then(() => {
//next(`/procmgr/login?redirect=${to.path}`);
next(`/login`);
NProgress.done();
});
} else {
next(`/login`);
NProgress.done();
}
} else {
//权限判断
}
}
}
});