JSPM

  • Created
  • Published
  • Downloads 108373
  • Score
    100M100P100Q160072F
  • License MIT

Document head manager for Vue 3. SSR ready.

Package Exports

  • @vueuse/head

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@vueuse/head) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@vueuse/head

Document head manager for Vue 3.

💛 Support the ongoing development of this project by becoming a GitHub Sponsor.

Installation

npm i @vueuse/head
# Or Yarn
yarn add @vueuse/head

Usage

Register the Vue plugin:

import { createApp } from 'vue'
import { createHead } from '@vueuse/head'

const app = createApp()
const head = createHead()

app.use(head)

app.mount('#app')

Manage head with the composition API useHead in your component:

<script>
import { defineComponent } from 'vue'
import { useHead } from '@vueuse/head'

export default defineComponent({
  setup() {
    useHead(() => ({
      title: `Website title`,
      meta: [
        {
          name: `description`,
          content: `Website description`,
        },
      ],
    }))
  },
})
</script>

Server-side rendering

import { renderToString } from '@vue/server-renderer'
import { renderHeadToString } from '@vueuse/head'

const appHTML = await renderToString(yourVueApp)

// `head` is created from `createHead()`
const { headTags, htmlAttrs, bodyAttrs } = renderHeadToString(head)

const finalHTML = `
<html${htmlAttrs}>

  <head>
    ${headTags}
  </head>

  <body${bodyAttrs}>
    <div id="app">${appHTML}</div>
  </body>

</html>
`

API

createHead()

Create the head manager instance.

useHead(() => HeadObj)

interface HeadObj {
  title?: string
  base?: Attrs
  meta?: Attrs[]
  link?: Attrs[]
  style?: Attrs[]
  script?: Attrs[]
  htmlAttrs?: Attrs
  bodyAttrs?: Attrs
}

interface Attrs {
  [attrName: string]: any
}

For meta tags, we use name and property to prevent duplicated tags, you can instead use the key attribute if the same name or property is allowed:

useHead({
  meta: [
    {
      property: 'og:locale:alternate',
      content: 'zh',
      key: 'zh',
    },
    {
      property: 'og:locale:alternate',
      content: 'en',
      key: 'en',
    },
  ],
})

To set the textContent of an element, use the children attribute:

useHead({
  style: [
    {
      children: `body {color: red}`,
    },
  ],
})

renderHeadToString(head: Head)

  • Returns: HtmlResult
interface HtmlResult {
  // Tags in `<head>`
  readonly headTags: string
  // Attributes for `<html>`
  readonly htmlAttrs: string
  // Attributes for `<body>`
  readonly bodyAttrs: string
}

Render the head manager instance to HTML tags in string form.

License

MIT © EGOIST