VUE添加路由进度条

npm install --save nprogress

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  let userToken = getCookie('User-Token') || '';
  // console.log(userToken, 'User-Token-router')
  if (!userToken) {
    // clearAllCookie();
    return window.location.href = `${process.env.VUE_APP_LOGIN_URL}?return_url=${window.location}`
  }

  // 登录直接放行
  if(to.name == 'login') {
    NProgress.done()
   return next()
  }

   // 白名单
   let whiteList = ['login', '404', 'notauth'] //404

   let isRouterWhiter = whiteList.some(item => {
     return item === to.name
   })
   if(isRouterWhiter) {
    NProgress.done()
     return next()
   }

  // 获取权限
  let getAuth = JSON.parse(getCookie('menus_auth')) || ''
  // console.log(getAuth, '--cookie中的menus_auth')
  let authList = []
  function checkList(list) {
    list.forEach(element => {
      authList.push(element.componentName)
      if(element.children.length > 0) {
        checkList(element.children)
      }
    });
  }
  if(getAuth.length !== 0 && getAuth != '') {
    checkList(getAuth)
  }else {
    const { data } = await queryUserPerTree(process.env.VUE_APP_SOURCE)
    // console.log(data)
    if(parseInt(data.code) === 200) {
      setCookie("menus_auth", JSON.stringify(data.data) || "", 1);
      getAuth = data.data
      // console.log(getAuth, '--获取的menus_auth')
      checkList(getAuth)
    }
  }
  
  let isRouter = authList.some(item => {
    return item === to.name
  })
  // console.log(isRouter, '--是否有此路由')
  // console.log(authList, '--获取到的权限')
  // console.log(to.name, '--当前跳转的路由')
  if(isRouter) {
    NProgress.done()
   return next()
  }else if(!isRouter && authList.length > 0){
    let aL = authList.filter(e => {return e != ''})
    NProgress.done()
   return next({name: aL[0]})
  }else {
    NProgress.done()
   return next('/notauth')
  }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})

你可能感兴趣的:(VUE添加路由进度条)