fix(hooks): [useId] SSR hydration error caused by id in vue@3.5+ (#18647)

This commit is contained in:
qiang 2024-10-27 15:49:43 +08:00 committed by GitHub
parent 0705f30364
commit f2a65850b4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 3 deletions

View File

@ -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,

View File

@ -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++}`