router.beforeEach((to, from, next) => {
if (getToken()) {
const hasArchLen = (store.state.menu.archList || []).length // 判断自建应用
!hasArchLen && store.dispatch('menu/sbaPage') // 判断自建应用--没有自建应用-提醒用户开通自建应用
}
routerJump(to, from, next)
})
function routerJump(to, from, next) {
// 判断用户需不需要获取权限
if (store.state.user.isGetRole) {
// 没有匹配到路由
debugger
if (to.matched.length === 0) {
next()
} else {
deleteParent(asyncRouter)
next()
}
} else {
store.dispatch('user/getAccountInfo').then((e) => {
// 用户信息
setCookie('LoginName', e.loginName)
store.commit('user/SET_USERINFO', e)
store.dispatch('user/getRolePermission').then((res) => {
router.addRoutes(res) // 动态添加可访问路由表
router.options.routes = asyncRouter.concat(router.options.routes)
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
})
}
}
function deleteParent(routerList) {
// 如果child没有 或者全部都是隐藏的 则删除父路由
for (let index = 0; index < routerList.length; index++) {
const element = routerList[index]
if (element.children && element.children.every((x) => x.hide || (x.children && x.children.length === 0))) {
routerList.splice(index, 1)
index--
} else if (element.children) {
deleteParent(element.children)
}
}
}
+ vuex
const actions = {
async getAccountInfo({ commit }) {
const result = await getAccountInfo() // 用户信息
const project = await listProject({ productNumber: 10006 })
if (!result) return
commit('SET_USERINFO', result.data)
commit('SET_PROJECTLIST', project.data)
if (project.data.length > 0 && !getCookie('mk-projectId')) {
setCookie('mk-projectId', project.data[0].projectId)
commit('SET_PROJECTID', project.data[0].projectId)
}
state.isGetRole = true // 获取到用户信息以后吧isGetRole 改为true 然后在刷新的时候或者重新进入再触发
const authType = result.data.config && result.data.config.authType ? result.data.config.authType : ''
localStorage.authType = authType
return {
...result.data
}
},
getRolePermission({ commit, state }) {
return new Promise((resolve, reject) => {
// 后续看productNumber 从getAccont 中获取还是根据token吧
getRolePermission({ productNumber: 10006 }).then(async (res) => {
const list = deepClone(asyncRouter)
const target = getPermissionList(list, res.data)
commit('SET_GETROLE', true)
resolve(target)
})
})
},
}
// 处理菜单路由
function getPermissionList(list, permissionMenu, arr = []) {
for (let item of list) {
let node = { ...item, children: [] }
if (item.mark) {
arr.push(node)
} else {
if (item.meta && item.meta.code) {
const idx = permissionMenu.findIndex((code) => code === item.meta.code)
idx > -1 && arr.push(node)
}
}
if (item.children && item.children.length) {
getPermissionList(item.children, permissionMenu, node.children)
}
}
return arr
}
菜单权限开发
于 2022-09-08 14:36:00 首次发布