前言
本文介绍的是全局前置守卫 router.beforeEach
,它常用作登录拦截,该函数会在每次路由跳转前执行,在此期间做一个登录判断,只有登录过后才具有访问路由的权限
全局前置守卫的回调接受三个参数
- to :即将要进入的目标
- from :当前导航正要离开的路由
- next :决定能够访问到的路由(该函数必须被调用一次)
实现
// 定义一个任何时候都可以访问的路由数组集合
const anyRoutes = ['/login', 'register', '/home', '/index'];
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('token');
if (anyRoutes.includes(to.path) || isLogin) {
next();
} else {
next('/login');
}
});