permission.js 2.23 KB
import { asyncRoutes, constantRoutes, resetRouter } from '@/router'

const state = {
    routes: [],
    addRoutes: false,
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = true
        state.routes = constantRoutes.concat(routes)
    },
    RESET_ROUTE: (state) => {
        state.addRoutes = false
    }
}

const actions = {
    // 添加全部菜单
    generateRoutes ({ commit }, getMenuInfo) {
        return new Promise(resolve => {
            // 将路由树数据转成数组结构
            let arr1 = []
            dfs(_.cloneDeep(asyncRoutes), node => arr1.push(node))
            _.each(arr1, i => {
                i.parentId = i.parentId ? i.parentId : null
            })
            //lodash intersectionBy方法取交集,并以参数1的数据返回
            let permission_arr = _.intersectionBy(arr1, getMenuInfo, 'id')
            // 将权限菜单数组转成路由树数据结构
            let permission_tree = array2Tree(permission_arr, null)
            commit('SET_ROUTES', permission_tree)
            resolve(permission_tree)
        })
    },
    // 重置路由
    resetRoutes ({ commit }) {
        commit('RESET_ROUTE')
    }
}
// 树转数组
function dfs (root, fVisit) {
    let stack = Array.isArray(root) ? [...root] : [root];
    while (stack.length) {
        let node = stack.pop();
        fVisit && fVisit(node);
        let children = node.children;
        if (children && children.length) {
            for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]);
        }
    }
}
// 数组转树
//需要插入父节点id,pid为null或'',就是找root节点,然后root节点再去找自己的子节点
function array2Tree (data, pid) {
    let res = [];
    data.forEach(item => {
        if (item.parentId === pid) {
            let itemChildren = array2Tree(data, item.id);
            if (itemChildren.length) item.children = itemChildren;
            res.push(item);
        }
    });
    // 菜单数据反转,保持一致
    res.reverse()
    _.each(res, c => {
        if (c.children && c.children.length > 0) {
            c.children.reverse()
        }
    })
    return res;
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}