fix(nuxt): only warn for useId if attrs were not rendered (#25770)

This commit is contained in:
Daniel Roe 2024-02-13 12:13:31 +00:00 committed by GitHub
parent 37d24eed7d
commit a1c1fda006
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -19,7 +19,7 @@ export function useId (key?: string): string {
if (!instance) { if (!instance) {
// TODO: support auto-incrementing ID for plugins if there is need? // TODO: support auto-incrementing ID for plugins if there is need?
throw new TypeError('[nuxt] `useId` must be called within a component.') throw new TypeError('[nuxt] `useId` must be called within a component setup function.')
} }
nuxtApp._id ||= 0 nuxtApp._id ||= 0
@ -29,9 +29,6 @@ export function useId (key?: string): string {
const instanceIndex = key + ':' + instance._nuxtIdIndex[key]++ const instanceIndex = key + ':' + instance._nuxtIdIndex[key]++
if (import.meta.server) { if (import.meta.server) {
if (import.meta.dev && instance.vnode.type && typeof instance.vnode.type === 'object' && 'inheritAttrs' in instance.vnode.type && instance.vnode.type.inheritAttrs === false) {
console.warn('[nuxt] `useId` is not compatible with components that have `inheritAttrs: false`.')
}
const ids = JSON.parse(instance.attrs[ATTR_KEY] as string | undefined || '{}') const ids = JSON.parse(instance.attrs[ATTR_KEY] as string | undefined || '{}')
ids[instanceIndex] = key + ':' + nuxtApp._id++ ids[instanceIndex] = key + ':' + nuxtApp._id++
instance.attrs[ATTR_KEY] = JSON.stringify(ids) instance.attrs[ATTR_KEY] = JSON.stringify(ids)
@ -48,6 +45,10 @@ export function useId (key?: string): string {
if (ids[instanceIndex]) { if (ids[instanceIndex]) {
return ids[instanceIndex] return ids[instanceIndex]
} }
if (import.meta.dev && instance.vnode.type && typeof instance.vnode.type === 'object' && 'inheritAttrs' in instance.vnode.type && instance.vnode.type.inheritAttrs === false) {
console.warn('[nuxt] `useId` might not work correctly with components that have `inheritAttrs: false`.')
}
} }
// pure client-side ids, avoiding potential collision with server-side ids // pure client-side ids, avoiding potential collision with server-side ids