Vue3使用递归组件封装El-Menu多级菜单

2023-09-06 13:51:36 浏览数 (1)

代码语言:javascript复制
<template>
    <aside class="menu">
        <el-scrollbar>
            <el-menu class="menu-main" router :default-active="route.path" unique-opened background-color="#18214C"
                text-color="#fff">
                <menuItem v-for="item in menuList" :item="item" :key="item.path" />
            </el-menu>
        </el-scrollbar>
    </aside>
</template> 
<script setup>
import menuItem from "./components/menuItem.vue"
import { useRoute } from "vue-router"
const route = useRoute()

const menuList = [
    {
        path: "/index",
        component: () => import("@/views/index.vue"),
        name: "index",
        meta: {
            title: "一级菜单"
        }
    },
    {
        path: "/level",
        name: "level",
        meta: {
            title: "多级菜单"
        },
        children: [
            {
                path: "/level/level-1",
                name: "level-1",
                meta: {
                    title: "多级菜单-1"
                },
                children: [
                    {
                        path: "/level/level-1/level-1-1",
                        component: () => import("@/views/level/level-1/level-1-1.vue"),
                        name: "level-1-1",
                        meta: {
                            title: "多级菜单-1"
                        }
                    }]
            },
            {
                path: "/level/level-2",
                component: () => import("@/views/level/level-2.vue"),
                name: "level-2",
                meta: {
                    title: "多级菜单-2"
                }
            }
        ]
    }
]


</script>
<style lang='scss' scoped>
.menu {
    height: 100vh;
    overflow: hidden;
    background-color: #18214C;

    &-main {
        border: none;
    }

    &-main:not(.el-menu--collapse) {
        width: 220px;
    }
}
</style>
代码语言:javascript复制
<template>
    <template v-if="item.meta && !item.meta.hidden">
        <el-sub-menu :index="item.path" :key="item.path" v-if="item?.children?.length > 0">
            <template #title>
                <el-icon>
                    <Aim />
                </el-icon>
                <span>{{ item.meta.title }}</span>
            </template>
            <menuItem v-for="child in item.children" :item="child" :key="child.path" />
        </el-sub-menu>
        <el-menu-item v-else :index="item.path">
            <el-icon>
                <Aim />
            </el-icon>
            <template #title>{{ item.meta.title }}</template>
        </el-menu-item>
    </template>
</template>
<script setup name="menuItem">
import { Aim } from '@element-plus/icons-vue'
const props = defineProps({
    item: {
        type: Object,
        default: () => { },
    },
})
</script>
<style lang='scss' scoped>
.el-menu-item.is-active {
    color: #fff;
    background: #2260FF;
}
</style>

0 人点赞