I'm using Vue webpack template: vue init webpack router-app
Setting meta titles in "router-app/src/router/index.js":
export default new Router({
mode: 'history',
routes: [
{
path: '*',
component: NotFoundComponent
},
{
path: '/',
name: 'LoginPage',
meta: { title: 'Home', bodyClass: 'dashboard' },
component: LoginPage
}
]
})
LoginPage.vue:
<template>
<form>
...
</form>
</template>
<script>
export default {
name: 'LoginPage',
data () {
return {
msg: 'Login Page'
}
}
}
</script>
But it doesn't affect my meta title at all. In a vue dev-tools (Chrome) i can see that $route
has my meta tags.
If you didn't include navigation guard, here is a function from a great article here. And its working fine.
If you only need to change the title you can do it like this
meta: {
title: 'About Page - Example App'
}
Insert this in your route.js
or (if not app.js
)
router.beforeEach((to, from, next) => {
const nearestWithTitle = to.matched.slice().reverse().find(r => r.meta && r.meta.title);
if (nearestWithTitle) document.title = nearestWithTitle.meta.title;
next();
});
If you need to change the meta tags' name and others as well then you need to whole function for flexibility
router.beforeEach((to, from, next) => {
const nearestWithTitle = to.matched.slice().reverse().find(r => r.meta && r.meta.title);
const nearestWithMeta = to.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
const previousNearestWithMeta = from.matched.slice().reverse().find(r => r.meta && r.meta.metaTags);
if (nearestWithTitle) document.title = nearestWithTitle.meta.title;
Array.from(document.querySelectorAll('[data-vue-router-controlled]')).map(el => el.parentNode.removeChild(el));
if (!nearestWithMeta) return next();
nearestWithMeta.meta.metaTags.map(tagDef => {
const tag = document.createElement('meta');
Object.keys(tagDef).forEach(key => {
tag.setAttribute(key, tagDef[key]);
});
tag.setAttribute('data-vue-router-controlled', '');
return tag;
})
.forEach(tag => document.head.appendChild(tag));
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With