zoukankan      html  css  js  c++  java
  • vue路由守卫配合权限,白名单

    router.beforeEach(async(to, from, next) => {
          // 进度条开始
          NProgress.start()
        
        
          // 确认用户是否已登录(获取它的token值,这里的getToken()是封装好的一个方法)
          const hasToken = getToken()
        
        
          if (hasToken) {//如果有token,说明是登录状态
            if (to.path === '/login') {//路由是/login页,那么直接跳转到首页
              next({ path: '/' })
              NProgress.done()  //进度条结束
            } else {//如果不是登录页
              // 确定用户是否已通过getInfo获得其权限角色
              const hasRoles = store.getters.roles && store.getters.roles.length > 0
              if (hasRoles) {//如果通过角色权限,继续访问
                next()      
              } else {//如果没有通过角色权限
                // alert('没有role')
                console.log('获取角色')
                try {
                  // get user info
                  // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
                  const { roles } = await store.dispatch('user/getInfo')
        
                  // generate accessible routes map based on roles
                  const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
        
                  // dynamically add accessible routes
                  router.addRoutes(accessRoutes)
        
                  // hack method to ensure that addRoutes is complete
                  // set the replace: true, so the navigation will not leave a history record
                  next({ ...to, replace: true })
                } catch (error) {
                  // remove token and go to login page to re-login
                  await store.dispatch('user/resetToken')
                  Message.error(error || 'Has Error')
                  next(`/login?redirect=${to.path}`)
                  NProgress.done()
                }
              }
            }
          } else {//如果没有token
            /* has no token*/
            // alert('没有token to.path=' + to.path)
        
            if (whiteList.indexOf(to.path) !== -1) {//白名单中有的路由,可以继续访问
              // in the free login whitelist, go directly
              next()
            } else {//否则,白名单中没有的路由,跳回首页
              // other pages that do not have permission to access are redirected to the login page.
              next(`/login?redirect=${to.path}`)
              NProgress.done()
            }
          }
        })
  • 相关阅读:
    升级ios 不能连原本的xcode /xcode不能抓帧/换xcode版本 build fail
    BlackBerry Key2 键盘扩展
    再议C风格变量声明
    怎样去除SVN中的某个版本之前的所有版本
    mysql 常用基础语句
    乱码问题
    sql server
    MySQL查询今天、昨天、上周、近30天、去年等的数据的方法
    java 时间转换
    sql server 日期
  • 原文地址:https://www.cnblogs.com/javascript9527/p/11857615.html
Copyright © 2011-2022 走看看