diff --git a/src/layouts/components/Menu/index.vue b/src/layouts/components/Menu/index.vue index 615cc863..42e1a918 100644 --- a/src/layouts/components/Menu/index.vue +++ b/src/layouts/components/Menu/index.vue @@ -20,6 +20,16 @@ const props = withDefaults( }, ) +// 用于缓存对象到 ID 的映射 +const idMap = new WeakMap() +// 获取对象的唯一 ID,如果已存在则返回缓存的 ID,否则生成新的 +function getUseId(obj: object): string { + if (!idMap.has(obj)) { + idMap.set(obj, useId()) + } + return idMap.get(obj)! +} + const activeIndex = ref(props.value) const items = ref({}) const subMenus = ref({}) @@ -32,7 +42,7 @@ const isMenuPopup = computed(() => { // 解析传入的 menu 数据,并保存到 items 和 subMenus 对象中 function initItems(menu: MenuProps['menu'], parentPaths: string[] = []) { menu.forEach((item) => { - const index = item.path ?? JSON.stringify(item) + const index = item.path ?? getUseId(item) if (item.children) { const indexPath = [...parentPaths, index] subMenus.value[index] = { @@ -144,6 +154,7 @@ watch(() => props.collapse, (value) => { provide(rootMenuInjectionKey, reactive({ props, + getUseId, items, subMenus, activeIndex, @@ -164,10 +175,10 @@ provide(rootMenuInjectionKey, reactive({ 'py-1': props.mode === 'vertical', })" > -