vue动态菜单路由配置

通过调用后台接口来配置导航栏菜单

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import db from '@/utils/localstorage'
import {getMenu} from '@/api/user'
import Layout from '@/layout'
// /导入路径下的组件
// const _import = require('./router/_import') //获取组件的方法 项目中修改的 
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

let asyncRouter

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  const userRouter = db.get('USER_ROUTER')
  if (hasToken) { // token存在
    if(to.path == '/login') {
      next({path: '/'})
      NProgress.done()
    } else {
      if(userRouter.length) { // //如果router存在
        next()
      } else { // 如果router不存在即清除路由的缓存
        console.log('router不存在')
        const params = {
          clientId: 'eval',
          // roleNames: '考核人'
          roleNames: 'admin,考核人,考核对象'
        }
        try{
          getMenu(params).then(res => {
            asyncRouter = res.data.menus
            store.commit('account/setRoutes',asyncRouter) // 存路由
            db.save('USER_ROUTER', asyncRouter)
            const menus = filterAsyncRouter(asyncRouter)
            router.addRoutes(menus)
            next({ ...to, replace: true })
          })
        }catch(error) {
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else { // token不存在
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

function filterAsyncRouter(asyncRouter) {
  const accessedRouters  = asyncRouter.filter(route => {
    if(route.component) {
      if(route.component == 'Layout') {
        route.component = Layout
      }else {
        route.component = view(route.component)
      }
    }
    if(route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
function view(path) {
  return (resolve) => require([`@/views${path}.vue`], resolve)
}
router.afterEach(() => {
  NProgress.done()
})

你可能感兴趣的:(elementui,javascript,vue.js)