@@ -20,6 +20,16 @@ const props = withDefaults(
2020 },
2121)
2222
23+ // 用于缓存对象到 ID 的映射
24+ const idMap = new WeakMap <object , string >()
25+ // 获取对象的唯一 ID,如果已存在则返回缓存的 ID,否则生成新的
26+ function getUseId(obj : object ): string {
27+ if (! idMap .has (obj )) {
28+ idMap .set (obj , useId ())
29+ }
30+ return idMap .get (obj )!
31+ }
32+
2333const activeIndex = ref <MenuInjection [' activeIndex' ]>(props .value )
2434const items = ref <MenuInjection [' items' ]>({})
2535const subMenus = ref <MenuInjection [' subMenus' ]>({})
@@ -32,7 +42,7 @@ const isMenuPopup = computed<MenuInjection['isMenuPopup']>(() => {
3242// 解析传入的 menu 数据,并保存到 items 和 subMenus 对象中
3343function initItems(menu : MenuProps [' menu' ], parentPaths : string [] = []) {
3444 menu .forEach ((item ) => {
35- const index = item .path ?? JSON . stringify (item )
45+ const index = item .path ?? getUseId (item )
3646 if (item .children ) {
3747 const indexPath = [... parentPaths , index ]
3848 subMenus .value [index ] = {
@@ -144,6 +154,7 @@ watch(() => props.collapse, (value) => {
144154
145155provide (rootMenuInjectionKey , reactive ({
146156 props ,
157+ getUseId ,
147158 items ,
148159 subMenus ,
149160 activeIndex ,
@@ -164,10 +175,10 @@ provide(rootMenuInjectionKey, reactive({
164175 'py-1': props.mode === 'vertical',
165176 })"
166177 >
167- <template v-for =" item in menu " :key =" item .path ?? JSON . stringify (item )" >
178+ <template v-for =" item in menu " :key =" item .path ?? getUseId (item )" >
168179 <template v-if =" item .meta ?.menu !== false " >
169- <SubMenu v-if =" item.children?.length" :menu =" item" :unique-key =" [item.path ?? JSON.stringify (item)]" />
170- <Item v-else :item =" item" :unique-key =" [item.path ?? JSON.stringify (item)]" @click =" handleMenuItemClick(item.path ?? JSON.stringify (item))" />
180+ <SubMenu v-if =" item.children?.length" :menu =" item" :unique-key =" [item.path ?? getUseId (item)]" />
181+ <Item v-else :item =" item" :unique-key =" [item.path ?? getUseId (item)]" @click =" handleMenuItemClick(item.path ?? getUseId (item))" />
171182 </template >
172183 </template >
173184 </div >
0 commit comments