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()
        }
      }
    })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM