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()
            }
          }
        })
  • 相关阅读:
    烂笔头@WP 的博文仅供自己学习的备忘录
    工具---搜索
    ubuntu---安装teamviewer和向日葵
    Ubuntu---标注工具 XXX-labelImg
    ubuntu---深度学习标注工具CasiaLabeler
    ubuntu---kazam安装
    ubuntu---notepadqq安装
    ubuntu---TeamViewer安装
    ubuntu---鼠标的乌龙事件
    ubuntu---终端下不显示 中文文字 的解决方法
  • 原文地址:https://www.cnblogs.com/javascript9527/p/11857615.html
Copyright © 2011-2022 走看看