router.beforeEach((to, from, next) => {
// console.log('IsLogin: ', store.state.IsLogin);
// console.log('to: ', to);
// console.log('from: ', from);
// console.log('next: ', next);
const nextRoute = [ '/home', '/notification'];
//跳转至上述3个页面
// /home
if ( nextRoute.indexOf(to.path) >= 0) {
// console.log( '跳转其他' , store.state.IsLogin );
//未登录
if (!localStorage.getItem('token')) {
// console.log('IsLogin',store.state.IsLogin);
// console.log('未登录,isLogin:', store.state.IsLogin);
router.push({ path: '/login' }).catch(e => {})
}
}
//已登录的情况再去登录页,跳转至首页
if (to.path === '/login') {
console.log('跳转login');
if (localStorage.getItem('token')) {
console.log('已登录,token:', localStorage.getItem('token'));
router.push({path: '/home' }).catch(e => {})
}
}
next();
});
beforeEach函数有三个参数:
to:router即将进入的路由对象
from:当前导航即将离开的路由
next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
localstorage.setItem设置token