vue-router路由守卫基本使用

vue-router路由守卫基本使用

作用

  1. 通过路由拦截,来判断用户是否登录,该页面用户是否有权限浏览

全局路由守卫

  1. 全局前置守卫:路由跳转前调用

    router.beforeEach((to,from,next)=>{
           
        console.log(to);  // 即将要跳转的路由
        console.log(from); // 即将要离开的路由
        next() // 一定要调用 执行下一个钩子 全部钩子执行完 跳转到地址栏上的路由
    })
    

vue-router路由守卫基本使用_第1张图片
在这里插入图片描述

router.beforeEach((to,from,next)=>{
     
    console.log(to);  
    console.log(from); 
    next(false) // 中断当前路由跳转
})
router.beforeEach((to,from,next)=>{
     
    console.log(to);  
    console.log(from); 
    next('/test') // 跳转到指定路由 此处代码写法错误 
})

跳转到指定路由,此处代码写法错误,会造成死循环直到浏览器栈溢出,调用next()的同时也会执行多一次beforeEach

正确写法是先判断要离开的路由是什么再跳转

router.beforeEach((to, from, next) => {
     
  console.log(to);
  console.log(from);
  if (to.path == "/home") {
     
    next('test');
    next({
      path: '/test' })  //或者这样写
  }
});
  1. 全局后置守卫:路由跳转之后再执行

    router.afterEach((to,from)=>{
           
        console.log(to);
        console.log(from);
    })
    

路由独享的守卫

在路由配置上直接定义 beforeEnter 守卫

const routes = [
  {
     
    path: "/home",
    component: () => import(/* webpackChunkName: "user" */ "../views/Home"),
    beforeEnter:(to,from,next)=>{
     
        console.log(to);
        console.log(from);
        next()
    }
  },
];

效果和beforeEach差不多

组件内的守卫

等要用到再来回顾

你可能感兴趣的:(vue)