这里主要是使用的router的类似钩子函数的router.beforeEach,在每次路由跳转之前判断是否有token,有token的无法访问到login登陆页面,没有token只能进入login页面。
注意这里需要在router/index.js 根目录下进行全局的注册,因为router在每个组件中都有涉及
router.beforeEach((to,from,next)=>{
const hasToken=getToken();
if (hasToken){
if (to.path=='/login'){
next({path:"/admin"}); //放行到/admin
}else{
next();// 继续执行接下来的操作
}
}else {
if (to.path=='/login'){
next();
}else {
next({path:"/login"});
}
}
})