Vue Reactivity

Master Vue and Unhead by following the best practices.

How Reactivity Works

When using any of the provided composables, such as useHead, full reactivity is provided out of the box.

All values are reactive and support:

  • ref
  • computed getter
  • computed (not recommended)
const myPage = ref({ description: 'This is my page' })
const title = ref('title')
const myScript = computed(() => ({
  src: 'https://example.com/script.js',
  defer: true,
}))
useHead({
  // ref (recommended)
  title,
  // computed getter (recommended)
  meta: [{ name: 'description', content: () => myPage.value.description },],
  // computed (not recommended)
  script: [computed(() => ({
    src: 'https://example.com/script.js',
    defer: true,
  }))],
})

It's recommended to avoid using computed, as you will have simpler and more performant code.

When using reactivity in SSR, only at the time of rendering the SSR tags will be refs be resolved.

When using reactivity in CSR, any ref changes will trigger a request to update the DOM.

Avoid Watch and useHead

Avoid wrapping useHead in a watcher.

// bad
watch((title) => {
  useHead({
    title,
  })
})

This is because each call of useHead will add a new entry, which has its own side effects.

Instead, use a computed getter.

// good
useHead({
  title: () => title
})
Did this page help you?