How to change page titles when using vue-router?
You can use a navigation guard with the router definition:
import Vue from 'vue';
const DEFAULT_TITLE = 'Some Default Title';
router.afterEach((to, from) => {
// Use next tick to handle router history correctly
// see: https://github.com/vuejs/vue-router/issues/914#issuecomment-384477609
Vue.nextTick(() => {
document.title = to.meta.title || DEFAULT_TITLE;
});
});
You'll need to change your export to:
const router = new Router({ ... });
...
export default router;
Or you can use an immediate watcher on your root component:
export default {
name: 'App',
watch: {
$route: {
immediate: true,
handler(to, from) {
document.title = to.meta.title || 'Some Default Title';
}
},
}
};
Advanced variant
Using vue-meta
first run
npm install vue-meta
and include it into your main.js;
import VueMeta from 'vue-meta'
Vue.use(VueMeta)
after doing so you can add a metaInfo()
method to every vue component, handling meta data;
metaInfo() {
return {
title: "Epiloge - Build your network in your field of interest",
meta: [
{ name: 'description', content: 'Epiloge is about connecting in your field of interest. Our vision is to help people share their knowledge, work, projects, papers and ideas and build their network through what they do rather where they live, study or work.'},
{ property: 'og:title', content: "Epiloge - Build your network in your field of interest"},
{ property: 'og:site_name', content: 'Epiloge'},
{property: 'og:type', content: 'website'},
{name: 'robots', content: 'index,follow'}
]
}
}
Furthermore this can be used for dynamic meta info;
export default{
name: 'SingleUser',
data(){
return{
userData: {},
...
aws_url: process.env.AWS_URL,
}
},
metaInfo() {
return {
title: `${this.userData.name} - Epiloge`,
meta: [
{ name: 'description', content: 'Connect and follow ' + this.userData.name + ' on Epiloge - ' + this.userData.tagline},
{ property: 'og:title', content: this.userData.name + ' - Epiloge'},
{ property: 'og:site_name', content: 'Epiloge'},
{ property: 'og:description', content: 'Connect and follow ' + this.userData.name + ' on Epiloge - ' + this.userData.tagline},
{property: 'og:type', content: 'profile'},
{property: 'og:url', content: 'https://epiloge.com/@' + this.userData.username},
{property: 'og:image', content: this.aws_url + '/users/' + this.userData.profileurl + '-main.jpg' }
]
}
},
...
}
Source: Medium - How to add dynamic meta-tags to your Vue.js app for Google SEO