diff --git a/packages/hooks/__tests__/use-id.test.tsx b/packages/hooks/__tests__/use-id.test.tsx index 65c5a45a1c..4060dc0aca 100644 --- a/packages/hooks/__tests__/use-id.test.tsx +++ b/packages/hooks/__tests__/use-id.test.tsx @@ -86,6 +86,9 @@ describe('useId warns in non-client environment with default idInjection', async ref: vi.fn(), computed: vi.fn(), })) + vi.doMock('@vueuse/core', () => ({ + computedEager: vi.fn(), + })) vi.doMock('@element-plus/utils', () => ({ debugWarn: mockWarn, isClient: mockIsClient, diff --git a/packages/hooks/use-id/index.ts b/packages/hooks/use-id/index.ts index 55dc05d5ee..583cc0fb7c 100644 --- a/packages/hooks/use-id/index.ts +++ b/packages/hooks/use-id/index.ts @@ -1,9 +1,9 @@ -import { computed, getCurrentInstance, inject, unref } from 'vue' +import { getCurrentInstance, inject, unref } from 'vue' +import { type MaybeRef, computedEager } from '@vueuse/core' import { debugWarn, isClient } from '@element-plus/utils' import { useGetDerivedNamespace } from '../use-namespace' import type { InjectionKey, Ref } from 'vue' -import type { MaybeRef } from '@vueuse/core' export type ElIdInjectionContext = { prefix: number @@ -38,7 +38,9 @@ usage: app.provide(ID_INJECTION_KEY, { } const namespace = useGetDerivedNamespace() - const idRef = computed( + + // NOTE: Here we use `computedEager` to calculate the id value immediately, avoiding inconsistent id generation due to the lazy feature of `computed` when server rendering. + const idRef = computedEager( () => unref(deterministicId) || `${namespace.value}-id-${idInjection.prefix}-${idInjection.current++}`