Taha

The Easy Way to Change Page Title in Vue

For any traditional website we build, we have to display a different page title for each different page we have. This can be simply done by changing the content of the <title> tag in our html code.

But for Single-Page Applications things are a little bit different. When the router changes to a different page component, the title should be changed programmatically using document.title = 'new title'.

Since this is going to be done for every page, let's create a clean, reusable solution using vue mixins.

The titleMixin

In your mixins directory create a new file called titleMixin.js and put this into it:

function getTitle(vm) {
  const { title } = vm.$options
  if (title) {
    return typeof title === 'function' ? title.call(vm) : title
  }
}

export default {
  created() {
    const title = getTitle(this)
    if (title) {
      document.title = title
    }
  }
}

Let's see how to use it

First, we have to install the mixin globally. You can do that in your main.js, like this:

import titleMixin from './mixins/titleMixin'

Vue.mixin(titleMixin)

Now you can use it in your component pages like this:

<script>
  export default {
    title: 'Foo Page'
  }
</script>

Or you can access the values of your vue instance by using a function instead of a string. For example:

<script>
  export default {
    title() {
      return `Foo Page — ${this.someValue}`
    },

    data() {
      return {
        someValue: 'bar'
      }
    }
  }
</script>

Note: credit goes to Evan You for his title mixin solution from the vue-hackernews-2.0 repo.

Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.