ant-design-vue中使用a-menu刷新页面后菜单仍选中高亮

目录

 一、Menu 所需参数

 二、API

 三、代码

概要:代码环境 vue3+antd

 一、Menu 所需参数

  1.  selectedKeys:当前选中的菜单项 key 数组
  2. openKeys:当前展开的 SubMenu 菜单项 key 数组
  3. openChange:SubMenu 展开/关闭的回调
  4. click:点击 MenuItem 调用此函数
  5. mode:菜单类型,现在支持垂直(vertical )、水平(horizontal )、和内嵌模式 (inline)三种

 二、API

 

 

 

三、代码

<a-menu
    :selectedKeys="[route.path]"
    :openKeys="openKeys"
    @openChange="onOpenChange"
    @click="menuClick"
    mode="inline"
    class="menu"
>
    <template v-for="(menuItem,index) in menus" :key="menuItem.path">
        <template v-if="menuItem.children && menuItem.children.length > 0">
            <a-sub-menu :key="menuItem.path">
                <template #title>
                    <span class="menu_title">
                        <component :is="menuItem.icon"></component>
                        <span>{
   
   { menuItem.title }}</span>
                    </span>
                </template>
                <a-menu-item v-for="(child, childIndex) in menuItem.children" :key="child.path">{
   
   { child.title }}</a-menu-item>
            </a-sub-menu>
        </template>
        <template v-else>
            <a-menu-item :key="menuItem.path">
                <component :is="menuItem.icon"></component>
                <span>{
   
   { menuItem.title }}</span>
            </a-menu-item>
        </template>
    </template>
</a-menu>
<script setup>
import {computed, ref, onMounted} from 'vue'
import {useRoute, useRouter} from "vue-router"

const router = useRouter()
const route = useRoute()

const selectedKeys = ref([])
const openKeys = ref([])
//获取你自己的菜单数据
const menus = computed(() => layoutStore.menuInfos)

const onOpenChange = keys => {
    let keyArr = []
    if (keys.length > 0) {
        //取最后一项,最后一项才是你当前展开的菜单
        keyArr.push(keys[keys.length - 1])
    }
    openKeys.value = keyArr
    sessionStorage.setItem('openKeys', JSON.stringify(keyArr))
 }

const menuClick = (item) => {
    router.push(item.key)
    //判断是否是一级菜单,一级菜单item.keyPath长度为1,二级菜单item.keyPath长度为2,清空二级菜单展开数组openKeys
    if (item.keyPath.length == 1) {
        sessionStorage.removeItem('openKeys')
        openKeys.value = []
    }
}

onMounted(() => {
    const openKey = sessionStorage.getItem('openKeys')
    if (openKey) {
        openKeys.value = JSON.parse(openKey)
    }
})

</script>

 注意:

  • 子菜单绑定的key要是path路径

猜你喜欢

转载自blog.csdn.net/csdnyp/article/details/125661006