vue-router

问:需要用户没有登录时先跳到登录页,怎么做?
一开始这样写:

router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('token');
    if(token != null){
        next();
    }
    else{
        next({
            path : '/login'
        });
    }
});

结果发现当用户没有登录时,页面路由不停跳转,怎么回事?
答:因为路由不停地走router.beforeEach里的else语句,跳到'/login'路由以后,又跳到'/login'了,这样就陷入死循环了,目前我的解决方案是在router.beforeEach里对'/login'路由进行特殊处理:

router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('token');
    if(to.path == '/login'){
        next();
    }
    if(token != null){
        next();
    }
    else{
        next({
            path : '/login'
        });
    }
});

你可能感兴趣的:(vue-router)