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.
🔗 Let’s stay connected!
- 𝕏 Twitter/X: https://twitter.com/tahazsh
- 🎥 YouTube: https://www.youtube.com/@tahazsh
- 🌐 Blog: https://tahazsh.com/