chore: add useHydratedHead

This commit is contained in:
userquin 2023-02-18 01:23:50 +01:00
parent a7cec9e67d
commit d6d413a191

View file

@ -1,5 +1,8 @@
import type { ComponentInternalInstance } from 'vue' import type { ComponentInternalInstance } from 'vue'
import { onActivated, onDeactivated, ref } from 'vue' import { onActivated, onDeactivated, ref } from 'vue'
import type { ActiveHeadEntry, HeadEntryOptions, UseHeadInput } from '@vueuse/head'
import type { HeadAugmentations } from '@nuxt/schema'
import { useHead } from '#head'
export const isHydrated = ref(false) export const isHydrated = ref(false)
@ -34,3 +37,25 @@ export function onReactivated(hook: Function, target?: ComponentInternalInstance
}, target) }, target)
onDeactivated(() => initial.value = false) onDeactivated(() => initial.value = false)
} }
export function useHydratedHead<T extends HeadAugmentations>(input: UseHeadInput<T>, options?: HeadEntryOptions): ActiveHeadEntry<UseHeadInput<T>> | void {
if (input && typeof input === 'object' && !('value' in input)) {
const title = 'title' in input ? input.title : undefined
if (process.server && title) {
input.meta = input.meta || []
if (Array.isArray(input.meta)) {
input.meta.push(
{ property: 'og:title', content: (typeof input.title === 'function' ? input.title() : input.title) as string },
)
}
}
else if (title) {
(input as any).title = () => isHydrated.value ? typeof title === 'function' ? title() : title : ''
}
}
return useHead(() => {
if (!isHydrated.value)
return {}
return resolveUnref(input)
}, options)
}