permission.js
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' })
NProgress.done()
} else {
if (store.state.permission.routes.length === 0) {
store.dispatch('GenerateRoutes').then(accessRoutes => {
// 根据roles权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
}).catch(err => {
store.dispatch('user/FedLogOut').then(() => {
Message.error(err)
next(`/login?redirect=${to.path}`)
})
})
} else {
next()
}
}
} else {
/* has no token */
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// next(`/login?redirect=${to.path}`)
next('/login')
NProgress.done()
}
}
})
layout/components/Sidebar/index
computed: {
...mapGetters([
'sidebar'
]),
routes() {
return this.$store.state.permission.routes
// return this.$router.options.routes
},
//...
}
store/modules/permission.js
import { constantRoutes } from '@/router'
import { getSystemMenu } from '@/api/user'
import Layout from '@/layout/index'
const permission = {
state: {
routes: [],
addRoutes: []
},
mutations: {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
},
actions: {
// 生成路由
GenerateRoutes({ commit }) {
return new Promise(resolve => {
// 向后端请求路由数据
getSystemMenu().then(res => {
res = res ? res : []
const accessedRoutes = filterAsyncRouter2(res)
accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
})
}
}
}
// 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter2(asyncRouterMap) {
function forFn(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].page_component !== '@/layout') {
arr[i].page_component = arr[i].page_component.replace('@/views/', '')
}
let obj = {
path: arr[i].page_path_key,
name: arr[i].page_name_key,
hidden: !arr[i].is_show_byplatform || !arr[i].is_show,
component: arr[i].page_component === '@/layout' ? Layout : loadView(arr[i].page_component),
meta: { title: arr[i].name, icon: arr[i].icon },
children: arr[i].childs && arr[i].childs.length > 0 ? arr[i].childs : []
}
arr[i] = obj
if (arr[i].children.length > 0) {
forFn(arr[i].children)
}
}
}
forFn(asyncRouterMap)
return asyncRouterMap
}
export const loadView = (view) => { // 路由懒加载
return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission