Vue Tip: Dynamically Change Page Title
To set the document title, we define the <title>
tag in our index.html
file:
In many applications, we have different routes and want to show a dedicated title for each route.
Unfortunately, this does not work out of the box, and we need to write some code to enable this functionality.
Let's take a look at an exemplary route configuration (check the Vue Router docs for more details about Vue Router):
We can use the beforeEach guard on the router instance to dynamically set the document title on each route. The beforeEach
guard adds a navigation guard that executes before any navigation:
Warning
In this example, we edit the page title using the document object, which is not advised when using server-side rendering (SSR). I recommend the vue-meta package if you are looking for an SSR-friendly solution. It offers a more adaptable and universal approach to handling page metadata in a Vue application.
Inside the navigation guard callback, we use document.title
to set the document's title. We use the nullish coalescing operator (??
) in combination with optional chaining (?.
) to set Default Title
if the meta
object or the title
is undefined.
Finally, we need to define the metadata on our routes:
At this point, we have updated our code to dynamically update the page title when the page changes. The following StackBlitz playground contains a running example:
We can improve the code by adding "more dynamic" page titles using route props:
We can access the route params via to.params
and set the document's title accordingly:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Access DOM in Watcher Callback After Vue Updated It
To access the DOM after Vue has updated it in a watcher callback, you can use the flush post option.'
Vue Tip: Typing Component Events
To declare emits with full type inference support, we can use the defineEmits API, which is automatically available inside <script setup>.