当访问某路由之前可以实现拦下来的效果。
下面的功能可以实现禁止进入“/about”路由,当想要进去的时候会跳转到主界面,其他的会正常。这里需要注意,一般加上这个else会更好,不然会报警告。
//全局前置守卫
router.beforeEach((to, from, next)=> {
console.log("to: ", to);
console.log("from: " , from)
if(to.path == "/about"){
next("/")
}else{
next()
}
})
实际使用:
// 导航全局守卫
router.beforeEach((to, from, next) => {
const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
// 登录或者注册界面 直接放行
if (to.path == '/login' || to.path == '/sign') {
next();
return;
}
// 没登陆就去登录
if ( userInfo == null) {
alert('您还没有登录,请先登录');
next('/login');
return;
}else{
if (to.path.indexOf('/zhao/') != -1 && userInfo.type != 1) {
// console.log(to.path)
alert('对不起,您无权访问....');
next(from.path)
return;
}
if (to.path.indexOf('/tou/') != -1 && userInfo.type != 2) {
console.log(userInfo)
alert('对不起,您无权访问....');
next(from.path)
return;
}
if (to.path.includes('/manage/') && userInfo.type != 0) {
// console.log('tou')
alert('对不起,您无权访问....');
next(from.path)
return;
}
next();
}
})