After refreshing the page using a-menu in ant-design-vue, the menu is still selected and highlighted.

Table of contents

 1. Menu required parameters

 2. API

 3. Code

Summary: Code environment vue3+antd

 1. Menu required parameters

  1.  selectedKeys : currently selected menu item key array
  2. openKeys : currently expanded SubMenu menu item key array
  3. openChange : Callback for SubMenu expansion/closing
  4. click : This function is called when clicking on the MenuItem
  5. mode : menu type, currently supports vertical ( vertical ), horizontal ( horizontal ), and inline mode (inline)

 2. API

 

 

 

3. Code

<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>

 Notice:

  • The key bound to the submenu must be the path

Guess you like

Origin blog.csdn.net/csdnyp/article/details/125661006