vue-router 高阶——导航守卫的使用

zhuanbike 2022-1-19 785

导航守卫在用户权限检查中特别常用,先上一段基础代码:

router.beforeEach((to, from, next) => {
  const pathArr=['/standard','/user'] //设置需要权限的路径,
  if (pathArr.indexOf(to.Path)!==-1){ //如果to.path在上面路径内,to.path是绝对路径,to.fullPath是带参数的 
    const token = sessionStorage.getItem('user')//获取session
          if(token){//如果有session 
            next()//放行
          }else{
            next('/login')//如果没有session跳转登录页面
          }
    }else{//如果to.path没有在在上面路径内,放行
      next()
    }
  }

子目录限制写法:

//导航守卫,只要发生了路由跳转,必然触发beforEach
router.beforeEach((to, from, next) => {
  const pathArr=['/standard','/user'] //设置需要权限的路径,
  if (to.fullPath.indexOf(pathArr[0])!==-1||to.fullPath.indexOf(pathArr[1])!==-1){ //如果to.path在上面路径内,to.path是绝对路径,to.fullPath是带参数的 
    const token = sessionStorage.getItem('user')//获取session
          if(token){//如果有session 
            next()//放行
          }else{
            next('/login')//如果没有session跳转登录页面
          }
    }else{//如果to.path没有在在上面路径内,放行
      next()
    }
  }

更多高级用法,参考文章:https://blog.csdn.net/qq_42778001/article/details/102477217

最新回复 (2)
  • zhuanbike 2022-2-15
    0 引用 2
    方法二的弊端 /standard1 这样无关的链接也会被守卫
  • zhuanbike 2022-2-15
    0 引用 3

    方法二最佳写法
    const pathArr=['/standard','/user','/user/','/standard/','/standard?','/user?']
    if (to.fullpath.indexOf(pathArr[2])!==-1||to.fullpath.indexOf(pathArr[3])!==-1||to.fullpath.indexOf(pathArr[4])!==-1||to.fullpath.indexOf(pathArr[5])!==-1||pathArr.indexOf(to.path)!-==-1){
    }

    但是这样好像又无法解决  user?=1这样非/的动态地址,如果有这样的需求智能吧 user? 也写在pathArr里面

发新帖