- read

Vue Tip: Dynamically change page title

John Philip 61

Vue Tip: Dynamically change page title

3: Using Vue Router Navigation Guards

John Philip
Level Up Coding
Published in
3 min read21 hours ago

--

When working on a Vuejs application, you may need to dynamically set the page title based on changing data to enhance the user experience. In this article, we will explore various methods for dynamically setting the page title in Vue.js.

1. useTitle from VueUse

VueUse offers the useTitle utility function to set the page title tag. We can leverage this utility function as shown in the code snippet below.

import { ref, computed, watch } from 'vue';
import { useTitle } from '@vueuse/core';

// Create a ref to hold the initial title
const initialTitle = ref('My Vue Application');

// Use the useTitle function to set the initial title
const title = useTitle(initialTitle.value);

// Create a reactive variable to track the current page
const currentPage = ref('Home');

// Watch for changes in the currentPage variable and update the document title accordingly
watch(currentPage, (newPage) => {
title.value = `My Vue App - ${newPage}`;
});

// Later in your component or application logic...
currentPage.value = 'About'; // This will update the document title to 'My Vue App - About'
currentPage.value = 'Contact'; // This will update the document title to 'My Vue App - Contact'

In this example:

  • We import the necessary functions and components from Vue and @vueuse/core.
  • We create a ref called initialTitle to hold the initial title value, which is set to ‘My Vue Application’.
  • We use the useTitle function to set the initial title based on the initialTitle ref.
  • We create a currentPage ref to track the current page in our application.
  • We use the watch function to watch for changes in the currentPage ref.
  • When the currentPage changes, we update the document title to include the current page name.
  • Later in our application logic, we can change the currentPage value to reflect the current page the user is on, and the document title will automatically update to include the new page name.

This example demonstrates how to dynamically change the page title based on the current page of your Vue…