ruoyi vue element 实现点击、返回首页收起已经展开的菜单栏

发布于:2025-09-05 ⋅ 阅读:(16) ⋅ 点赞:(0)

问题描述

ruoyi VUE菜单有一个BUG,当我们点击其它按钮或者首页的时候,已经展示的一级菜单是不会自动收缩的。这个问题也导致很多开发者把一级菜单都换成了二级菜单。

解决方案 

// src/layout/components/Sidebar/index.vue

<template>
    <div :class="{ 'has-logo': showLogo }"
        :style="{ backgroundColor: settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground }">
        <logo v-if="showLogo" :collapse="isCollapse" />
        <el-scrollbar :class="settings.sideTheme" wrap-class="scrollbar-wrapper">
            <el-menu ref="menu" @open="handleOpen" :default-active="activeMenu" :collapse="isCollapse"
                :background-color="settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground"
                :text-color="settings.sideTheme === 'theme-dark' ? variables.menuColor : variables.menuLightColor"
                :unique-opened="true" active-text-color="#fff" :collapse-transition="false" mode="vertical">
                <sidebar-item v-for="(route, index) in sidebarRouters" :key="route.path + index" :item="route"
                    :base-path="route.path" />
            </el-menu>
        </el-scrollbar>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import Logo from "./Logo";
import SidebarItem from "./SidebarItem";
import variables from "@/assets/styles/variables.scss";

export default {
    components: { SidebarItem, Logo },
    data() {
        return {
            keyIndex: 0,
        };
    },
    watch: {
        $route(to, from) {
            this.handleOpen(from.path);
            if (this.$route.path === '/index') {
                this.$refs.menu.close(this.keyIndex);
            }
        }
    },
    methods: {
        handleOpen(key) {
            let index = key.split('/');
            this.keyIndex = `/${index[1]}`;
        }
    },
    computed: {
        ...mapState(["settings"]),
        ...mapGetters(["sidebarRouters", "sidebar"]),
        activeMenu() {
            const route = this.$route;
            const { meta, path } = route;
            // if set path, the sidebar will highlight the path you set
            if (meta.activeMenu) {
                return meta.activeMenu;
            }
            return path;
        },
        showLogo() {
            return this.$store.state.settings.sidebarLogo;
        },
        variables() {
            return variables;
        },
        isCollapse() {
            return !this.sidebar.opened;
        }
    }
};
</script>


网站公告

今日签到

点亮在社区的每一天
去签到