vue3 左侧菜单栏默认展开关闭
<el-menu class="mainMenu" router background-color="transparent" active-text-color="#fff" :unique-opened="true" :collapse-transition="false" :collapse="getIndexFlag" :default-active="activeIndex" :mode="navDirection == 'horizontal' ? 'horizontal' : 'vertical'" > <MenuItem v-for="(val, index) in state.menuList" :key="val.id" :menu="val" ></MenuItem> </el-menu>
// 初始化 function init() { // 从页面任意入口跳转或浏览器访问url,菜单高亮 activeIndex.value = route.path; } watch( () => router.currentRoute.value, value => { init(); } ); onMounted(() => { // 初始化 init(); });
key:需要设置为 id,而非index,否则会导致router.push跳转页面时,左侧菜单栏默认展开关闭有问题
menuItem组件:
<template> <template v-if="menu.children && menu.children.length > 0"> <el-sub-menu :index="menu.url || menu.id.toString()"> <template #title> <i v-if="menu.icon" :class="`font_family iconfont ${menu.icon}`"></i> <span>{{ menu.name }}</span> </template> <MenuItem v-for="item in menu.children" :key="item.id" :menu="item" ></MenuItem> </el-sub-menu> </template> <template v-else> <el-menu-item :index="menu.url || menu.id.toString()"> <i v-if="menu.icon" :class="`font_family iconfont ${menu.icon}`"></i> <span>{{ menu.name }}</span> </el-menu-item> </template> </template> <script lang="ts" setup> defineProps({ menu: { type: Object, required: true, }, }); </script>