vue-router根据权限动态添加相关路由

  1. 云栖社区>
  2. 博客>
  3. 正文

vue-router根据权限动态添加相关路由

烟海之蓝 2019-07-25 18:26:35 浏览848
展开阅读全文

在有权限的项目里,需要根据权限动态添加路由,使用addRoutes方法

import Vue from 'vue'
import Router from 'vue-router'
import Store from '../store'

import routes, {asyncRouterMap} from './routers.js'
Vue.use(Router)

let router = new Router({
  // mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
  routes
})
let flag = true // 只动态添加一次路由,防止进入回调地狱,当然也可以根据别的状态来判断
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (flag) {
      flag = false
      Store.dispatch('getMenu').then(() => {
        let routes = filterRouter(asyncRouterMap, Store.state.menuList)
        router.addRoutes(routes)
        next({...to, replece: true}) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      }).catch(() => {
        next({path: '/login'})
      })
    } else {
      next()
    }
  }
})

const filterRouter = (asyncRouter, menu) => {
  asyncRouter.children = asyncRouter.children.filter(item => {
    return menu.some(i => {
      if (i.children && i.children.length) {
        return i.children.some(k => {
          return k.path === item.path
        })
      } else {
        return i.path === item.path
      }
    })
  })
  
  return [asyncRouter]
}

export default router

网友评论

登录后评论
0/500
评论
烟海之蓝
+ 关注