From 5160da30858ba9d16fc05c15894ea434235962de Mon Sep 17 00:00:00 2001 From: Hooray <304327508@qq.com> Date: Sat, 7 Jun 2025 10:20:56 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BD=BF=E7=94=A8=20`useId`=20?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=8F=9C=E5=8D=95=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/layouts/components/Menu/index.vue | 19 +++++++++++++++---- src/layouts/components/Menu/sub.vue | 7 ++++--- src/layouts/components/Menu/types.ts | 1 + 3 files changed, 20 insertions(+), 7 deletions(-) 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', })" > -