Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage page titles dynamically in Vuejs?

Tags:

laravel

vue.js

I build an application. I have a header with the title of my page. Currently, I use view-router to define my titles.

{
    path: '/events',
    name: 'events',
    component: Events,
    meta: {
        title: 'Liste des événements'
    }
}

And in my blade view, in my header.blade.php I'm doing this to display the title

 <h2 class="header__title title-header">
    @{{ $route.meta.title }}
 </h2>

It work BUT when I have a dynamic data, necessarily, it does not work. For example, when I post a post, how can I do to earn my title?

    {
    path: '/events/:id',
    component: Event,
    name: 'Event',
    meta: {
        title: 'my dynamic title',
        page: 'event',
    },

How to recover the title of the post page? I have the name of the post in my post, but I can not access it from my header ...

enter image description here

I do not have access to the other components. These are components coming from element-ui.

Thank you in advance

like image 822
Jeremy Avatar asked Dec 14 '22 13:12

Jeremy


1 Answers

In your router, before export default router you can add

router.beforeEach((toRoute, fromRoute, next) => {
  window.document.title = toRoute.meta && toRoute.meta.title ? toRoute.meta.title : 'Home';

  next();
})

This will read the meta title if it exists and it will update the page title.

Or you can add it like this

const router = new Router({
  beforeEach(toRoute, fromRoute, next) {
    window.document.title = toRoute.meta && toRoute.meta.title ? toRoute.meta.title : 'Home';

    next();
  },
  routes: [
    ...
  ]
})

Don't forget to change the default title value from Home to something else - maybe name of your project

like image 181
ljubadr Avatar answered Dec 18 '22 00:12

ljubadr