vue路由守卫

全局守卫:

//全局守卫写在main中
//router对象调用
//.beforeEach((进入到哪一个路由,从哪一个路由离开,对应的函数)=>{})
router.beforeEach((to,form,next) =>{
//如果进入到的路由是登录页或者注册页面,则正常展示
if(to.path == '/login' || to.path == '/register' ){
  next();
}else if( !(localStorage.getItem('token')) ){
  alert("还没有登录,请先登录!");
  next('/login'); //转入login登录页面,登录成功后会将token存入localStorage
}else{
  next();
}
})

路由独享守卫:
//路由独享守卫,写在router路由中
{path:"/admin",name:"admin",component:admin,
//beforeEnter(to,form.next)=>{判断是否登陆代码},点击进入admin也面时,路由独享守卫启用
beforeEnter:(to,form,next)=>{
  //alert('非登陆状态,不能访问此页面!');
  //next('/login');
  //判断是否登录 store.gettes.isLogin === false
  if(to.path == '/login' || to.path == '/register' ){
    next();
  }else{
    alert("还没有登录,请先登录!");
    next('/login');
}
}
},

组件内守卫:
/*组件内守卫,写在组件中
组件内守卫使用beforeRouteEnter:(to,form,next)=>{代码}方法,
注意:该方法是在页面加载前执行。拿不到this.name的值,
利用好next的回调参数,拿到对应的内容,这个时候请使用vm.name,异步加载*/
beforeRouteEnter:(to,form,next)=>{
  // alert("hello" + this.name);
  // next();
  //to和form,可以判断要进入的路由名称,从哪个路由离开
  next(vm => {
  alert("Hello"+vm.name);
  })
}

//beforeRouteLeave:(to,form,next)=>{代码}方法,在用户离开页面前加载。
beforeRouteLeave:(to,form,next)=>{
  if(confirm("确定离开吗?") == true ){ //询问是否离开==true
    next(); //确认离开
  }else{
    next(false); //false不离开
  }
}

后置钩子守卫:

//后置钩子守卫,不常用!没有next参数,写在main.js中
router.afterEach((to,form) => {
	alert("after Each方法")
})
转自:https://blog.csdn.net/weixin_43848576/article/details/93722997
原文地址:https://www.cnblogs.com/xzybk/p/11791831.html