From f2a65850b431a2dc0ff960291d30be448e92586c Mon Sep 17 00:00:00 2001 From: qiang Date: Sun, 27 Oct 2024 15:49:43 +0800 Subject: [PATCH] fix(hooks): [useId] SSR hydration error caused by id in vue@3.5+ (#18647) --- packages/hooks/__tests__/use-id.test.tsx | 3 +++ packages/hooks/use-id/index.ts | 8 +++++--- 2 files changed, 8 insertions(+), 3 deletions(-) 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++}`