Vue中的3种路由守卫

450 阅读1分钟

注:要进行下一步操作一定要加next()方法哦!!!

1、全局路由守卫

router.beforeEach((to, from, next) => {
  // 判断路由是否需要守卫
  if(to.meta.auth) {

    //是否登录
    if(window.isLogin) {
      next();
    } else {
      next('/login?redirect=' + to.fullPath) // redirect to.fullPath 回到之前的页面
    }
  } else {
    next();
  }
});

2、局部路由守卫 【进入路由时】 (注:写在router具体路由的配置中)

beforeEnter: ((to, from, next) => {
  //是否登录
  if (window.isLogin) {
    next();
  } else {
    next('/login?redirect=' + to.fullPath) // redirect to.fullPath 回到之前的页面
  }
});

3、组件路由守卫 (注:写在组件中,和data(){}方法平级的任意位置)

  • A、组件路由守卫 之 进入路由时,【组件实例还没渲染,this还不能用哦,要用next((vc)=>{})回调函数传回来的 vc === VueComponent】
beforeRouteEnter(to, from, next) {
  next(vc => {
    console.log(vc); // 这里的vc就相当于this
    vc.id = vc.$route.params.id;
    if (vc.id) {
      vc.getUserInfo();
    }
  });
},
  • B、组件路由守卫 之 变化路由时,【组件实例已渲染,this可用】
beforeRouteUpdate(to, from, next) {
  console.log("路由发生变化了!");
  next();
},
  • C、组件路由守卫 之 离开路由时,【组件实例已渲染,this可用】
beforeRouteLeave(to, from, next) {
  console.log(to.fullPath);
  next();
},