Nuxt/docs/content/2.guide/2.features/4.head-management.md

89 lines
2.6 KiB
Markdown
Raw Normal View History

# Head Management
Out-of-the-box, Nuxt provides good default values for `charset` and `viewport` meta tags, but you can override these if you need to, as well as customize other meta tags for your site in several different ways.
:ReadMore{link="/api/configuration/nuxt.config#head"}
## `useHead` Composable
Within your `setup` function, you can call `useHead` with an object of meta properties with keys corresponding to meta tags: `title`, `titleTemplate`, `base`, `script`, `style`, `meta` and `link`, as well as `htmlAttrs` and `bodyAttrs`. There are also two shorthand properties, `charset` and `viewport`, which set the corresponding meta tags. Alternatively, you can pass a function returning the object for reactive metadata.
For example:
```vue
<script setup>
useHead({
titleTemplate: 'My App - %s', // or, title => `My App - ${title}`
viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
charset: 'utf-8',
meta: [
{ name: 'description', content: 'My amazing site.' }
],
bodyAttrs: {
class: 'test'
}
})
</script>
```
::ReadMore{link="/api/composables/use-head"}
::
## Meta Components
2021-11-21 12:31:44 +00:00
Nuxt provides `<Title>`, `<Base>`, `<Script>`, `<Style>`, `<Meta>`, `<Link>`, `<Body>`, `<Html>` and `<Head>` components so that you can interact directly with your metadata within your component's template.
Because these component names match native HTML elements, it is very important that they are capitalized in the template.
`<Head>` and `<Body>` can accept nested meta tags (for aesthetic reasons) but this has no effect on _where_ the nested meta tags are rendered in the final HTML.
For example:
<!-- @case-police-ignore html -->
```vue{}[app.vue]
<script setup>
const title = ref('Hello World')
</script>
<template>
<div>
<Head>
<Title>{{ title }}</Title>
<Meta name="description" :content="title" />
<Style type="text/css" children="body { background-color: green; }" />
</Head>
<h1>{{ title }}</h1>
</div>
</template>
```
## Example: usage with definePageMeta
You can use `definePageMeta` along with `useHead` to set metadata based on the current route.
For example, you can first set the current page title (this is extracted at build time via a macro, so it can't be set dynamically):
```vue{}[pages/some-page.vue]
<script setup>
definePageMeta({
title: 'Some Page'
})
</script>
```
And then in your layout file, you might use the route's metadata you have previously set:
```vue{}[layouts/default.vue]
<script setup>
const route = useRoute()
useHead({
meta: [{ name: 'og:title', content: `App Name - ${route.meta.title}` }]
})
</script>
```
2022-04-09 09:25:13 +00:00
:LinkExample{link="/examples/composables/use-head"}