vue-element-admin 项目中,获取当前左侧菜单栏的Id

发布时间 2023-10-24 09:22:41作者: 小蘑菇123

 

 找到 store/modules/permission.js(需要后端在返回的菜单中,添加Id):

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 => {
                // 向后端请求路由数据
                getRouters().then(res => {
                    const accessedRoutes = filterAsyncRouter(res.data);
                    accessedRoutes.push({ path: '*', redirect: '/401', hidden: true })
                    commit('SET_ROUTES', accessedRoutes)
                    resolve(accessedRoutes)
                })
            })
        }
    }
}

// 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
    return asyncRouterMap.filter(route => {
        // console.log(route.menuId);
        if (route.component) {
            // Layout组件特殊处理
            route.meta.menuId = route.menuId
            if (route.component === 'Layout') {
                route.component = Layout
            } else {
                route.component = loadView(route.component)
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })
}

找到 layout/components/Sidebar/index.js:

activeMenu() {
    const route = this.$route;
    console.log(route);
    if (route.meta.menuId) {
        localStorage.setItem("menuId", route.meta.menuId);
    }
    const { meta, path } = route
    // if set path, the sidebar will highlight the path you set
    if (meta.activeMenu) {
        return meta.activeMenu
    }
    return path
},

这样,在点击菜单的时候,就能获取到当前菜单对应的Id了