menuback 2.68 KB
import axios from '../../util/ajax'
import {asyncRouterMap, constantRouterMap } from '@/router'
/**
 * 获取路由列表
 */
function getMenuInfo(token) {
  return  new Promise((reslove, reject) =>{
    axios.get(IP +  "/api/v1/auth/apps/" + 'edd4abed322af106f0a06e2204202d79' + "/menus?shape=list",{
      headers: {
        'authorization': localStorage.getItem('atoken')
      },
    }).then(response => {
      reslove(response);
    })
  });
}

/**
 * 判断是否有权限
 * @param {*} router
 * @param {*} roles
 */
function hasPerminssion(router, roles) {
  let status = false
  if (roles) {
    roles.forEach(ele => {
      if (ele.path == router.path) {
        status = true;
        return false;
      }
    })
  }
  return status
}

/**
 * 根据后台返回的路由权限
 * 动态匹配路由
 * @param {*} asyncRouterMap
 * @param {*} roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const newData = [];
  // return routers
  asyncRouterMap.forEach(ele => {
    let obj = {};
    if (hasPerminssion(ele, roles)) {
      obj['path'] = ele.path;
      obj['name'] = ele.name;
      obj['component'] = ele.component;
      if (ele.children && ele.children.length > 0) {
        obj['children'] = filterAsyncRouter(ele.children, roles)
      } else {
        obj['children'] = []
      }
    } else {
      return false
    }
    newData.push(obj)
  });
  return newData
}
/**
 * 根据路由和当前跳转key(路由路径)
 * 获取第三级路由
 * @param {*} router
 * @param {*} key
 */
function filterTwoMenu(router, key) {
  let data = [],
  state = true;
  router.forEach(e => {
    if(e.path == key)
      if(e.children) {
        data = e.children
      } else {
        data = [];
      }
  })
  return data;
}

const menu = {
  state: {
    routers: constantRouterMap,
    addRouter: [],
    threeMenu:[],
  },
  mutations:{
    SET_ROUTERS: (state, routers) => {
      state.addRouter = routers;
      state.routers = constantRouterMap.concat(routers);
    },
    SET_THREEMENU: (state, routers) => {
      state.threeMenu = routers;
    },

  },
  actions: {
    GetMenuRole({ commit, state}) {
      return new Promise((resolve, reject) => {
        getMenuInfo().then(response => {
          let accessedRouters = filterAsyncRouter(asyncRouterMap,response.data.list_data);
          // commit('SET_ROUTERS', accessedRouters);
          commit('SET_ROUTERS', accessedRouters);

          resolve(accessedRouters);
        })
      })
    },
    GetTwoMenu({commit, state},data) {
      return new Promise((reslove,reject) => {
        const tmenus = filterTwoMenu(state.routers, data);
        commit('SET_THREEMENU', tmenus);
        reslove(tmenus);
      })
    },

  },

}

export default menu