Dynamic Titles on every page

How to make dynamic titles on every pages based on constants data.
2 Replies
kapa.ai
kapa.ai3w ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To create dynamic titles on every page in Nuxt based on constants data, you should use the useHead composable or definePageMeta macro within each page component. Both approaches support reactivity and allow you to reference constants or computed values. Example using useHead and a constant: Suppose you have a constants file:
// constants/site.js
export const SITE_NAME = 'My Awesome Site'
// constants/site.js
export const SITE_NAME = 'My Awesome Site'
Then, in your page component:
<script setup lang="ts">
import { SITE_NAME } from '~/constants/site'

const pageTitle = 'About Us' // This could be dynamic per page

useHead({
title: `${pageTitle} - ${SITE_NAME}`
})
</script>
<script setup lang="ts">
import { SITE_NAME } from '~/constants/site'

const pageTitle = 'About Us' // This could be dynamic per page

useHead({
title: `${pageTitle} - ${SITE_NAME}`
})
</script>
Or, for more flexibility, use a title template in app.vue:
<script setup lang="ts">
import { SITE_NAME } from '~/constants/site'

useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - ${SITE_NAME}` : SITE_NAME
}
})
</script>
<script setup lang="ts">
import { SITE_NAME } from '~/constants/site'

useHead({
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - ${SITE_NAME}` : SITE_NAME
}
})
</script>
Then, on each page, set the title with useHead or definePageMeta:
<script setup lang="ts">
useHead({
title: 'About Us'
})
</script>
<script setup lang="ts">
useHead({
title: 'About Us'
})
</script>
or
<script setup lang="ts">
definePageMeta({
title: 'About Us'
})
</script>
<script setup lang="ts">
definePageMeta({
title: 'About Us'
})
</script>
This way, every page will have a dynamic title based on your constants and the page-specific title. For more advanced templating, you can use templateParams with useHead as shown in the documentation Dynamic Title and Features.
Reactivity is supported, so you can use computed values or refs if your constants are reactive or change at runtime Features.
---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?