menu.js 1.87 KB
import {asyncRouterMap, constantRouterMap } from '@/router/index.js'
import defultrouter from "@/router/index.js";


/**
 * 判断是否有权限
 * @param {*} router
 * @param {*} roles
 */
function hasPerminssion(router, roles) {
  if (router.children && router.children.length > 0) {
    if (existsChildren(router, roles)) {
      return true;
    }
  }
  let status = false;
  // let status = true
  if (roles) {
    for (let i = 0; i < roles.length; i++) {
      if (roles[i].path === router.path) {
        status = true;
        break;
      }
    }
  }
  return status;
}

/**
 * 根据后台返回的路由权限
 * 动态匹配路由
 * @param {*} asyncRouterMap
 * @param {*} roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  var newData = [];
  // return routers
  asyncRouterMap.forEach((ele, index) => {
    roles.map(m => {
      if (ele.path == m.path) {
        let obj = ele;
        if (m.children && m.children.length > 0) {
          obj.children = filterAsyncRouter(ele.children, m.children);
        } else {
          obj.children = []
        }
        newData.push(obj);
      }
    });
  });
  return newData;
}

const menu = {
  state: {
    routers: constantRouterMap,
    addRouter: [],
    threeMenu: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouter = routers;
      state.routers = constantRouterMap.concat(routers);
      defultrouter.addRoutes(routers); //合并路由
    },
    SET_THREEMENU: (state, routers) => {
      state.threeMenu = routers;
    }
  },
  actions: {
    GetMenuRole({ commit, state }, data) {
      if (data === "") {
        commit("SET_ROUTERS", []);
        return;
      } else {
				console.log('aaa',data)
        let accessedRouters = filterAsyncRouter(asyncRouterMap, data);
        console.log(accessedRouters)
        commit("SET_ROUTERS", accessedRouters);
      }
    }
  }
};

export default menu;