useHead composable 允许你以编程化和响应式的方式管理你的 head 标签,由Unhead提供支持。它允许你自定义 HTML 文档 <head> 部分中的 meta 标签、链接、脚本和其他元素。
<script setup lang="ts">
useHead({
title: 'My App',
meta: [
{ name: 'description', content: 'My amazing site.' },
],
bodyAttrs: {
class: 'test',
},
script: [{ innerHTML: 'console.log(\'Hello world\')' }],
})
</script>
useHeadSafe。useHead 的属性可以是动态的,接受 ref、computed 和 reactive 属性。meta 参数也可以接受一个返回对象的函数,以使整个对象具有响应性。export function useHead (meta: MaybeComputedRef<MetaObject>): ActiveHeadEntry<UseHeadInput>
interface MetaObject {
title?: string
titleTemplate?: string | ((title?: string) => string)
base?: Base
link?: Link[]
meta?: Meta[]
style?: Style[]
script?: Script[]
noscript?: Noscript[]
htmlAttrs?: HtmlAttributes
bodyAttrs?: BodyAttributes
}
interface ActiveHeadEntry<Input> {
/**
* Updates the entry with new input.
*
* Will first clear any side effects for previous input.
*/
patch: (input: Input) => void
/**
* Dispose the entry, removing it from the active head.
*
* Will queue side effects for removal.
*/
dispose: () => void
}
请参阅@unhead/schema获取更详细的类型。
meta: 一个对象,接受 head 元数据属性,用于自定义页面的 <head> 部分。所有属性都支持响应式值(ref、computed、reactive)或可以是一个返回元数据对象的函数。
| 属性 | 类型 | 描述 |
|---|---|---|
title | string | 设置页面标题。 |
titleTemplate | string | ((title?: string) => string) | 配置一个动态模板来定制页面标题。可以是一个带有 %s 占位符的字符串,也可以是一个函数。 |
base | Base | 设置文档的 <base> 标签。 |
link | Link[] | 链接对象数组。每个元素被映射到一个 <link> 标签,其中对象的属性对应于 HTML 属性。 |
meta | Meta[] | Meta 对象数组。每个元素被映射到一个 <meta> 标签,其中对象的属性对应于 HTML 属性。 |
style | Style[] | 样式对象数组。每个元素被映射到一个 <style> 标签,其中对象的属性对应于 HTML 属性。 |
script | Script[] | 脚本对象数组。每个元素被映射到一个 <script> 标签,其中对象的属性对应于 HTML 属性。 |
noscript | Noscript[] | Noscript 对象数组。每个元素被映射到一个 <noscript> 标签,其中对象的属性对应于 HTML 属性。 |
htmlAttrs | HtmlAttributes | 设置 <html> 标签的属性。每个对象属性都映射到相应的属性。 |
bodyAttrs | BodyAttributes | 设置 <body> 标签的属性。每个对象属性都映射到相应的属性。 |
此 composable 不返回值。它将 head 元数据注册到 Unhead,由 Unhead 管理实际的 DOM 更新。
<script setup lang="ts">
useHead({
title: 'About Us',
meta: [
{ name: 'description', content: 'Learn more about our company' },
{ property: 'og:title', content: 'About Us' },
{ property: 'og:description', content: 'Learn more about our company' },
],
})
</script>
<script setup lang="ts">
const profile = ref({ name: 'John Doe' })
useHead({
title: computed(() => profile.value.name),
meta: [
{
name: 'description',
content: computed(() => `Profile page for ${profile.value.name}`),
},
],
})
</script>
<script setup lang="ts">
const count = ref(0)
useHead(() => ({
title: `Count: ${count.value}`,
meta: [
{ name: 'description', content: `Current count is ${count.value}` },
],
}))
</script>
<script setup lang="ts">
useHead({
link: [
{
rel: 'stylesheet',
href: 'https://cdn.example.com/styles.css',
},
],
script: [
{
src: 'https://cdn.example.com/script.js',
async: true,
},
],
})
</script>
<script setup lang="ts">
const isDark = ref(true)
useHead({
htmlAttrs: {
lang: 'en',
class: computed(() => isDark.value ? 'dark' : 'light'),
},
bodyAttrs: {
class: 'themed-page',
},
})
</script>