在有权限的项目里,需要根据权限动态添加路由,使用
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