3
votes

I'm using Vue Router and setting the meta object field, which is used to set the page title and description.

Right now I set up routes like this:

[...
{
   path: '/page1',
   component: Page1Component,
   meta: {
      title: 'Title for page1'
   }
}
...]

and then synchronize this with the DOM:

router.beforeEach((to, from, next) => {
    document.title = to.meta.title;
    next();
});

One of my routes, I want to use a query string in the title, but I can't pass a function to the meta object. Is there a way this can be done, without defining the title in the component?

For example, what I'd want to do:

[...
{
   path: '/page1',
   component: Page1Component,
   meta: (route) => {
      title: `dynamic title is ${route.query.param}`
   }
}
...]
2

2 Answers

4
votes

VueRouter doesn't support setting a route's meta property to be a function like you're trying to do.

But you could have your title property be able to also be set as a function which takes in your route as a param:

{
   path: '/page1',
   component: Page1Component,
   meta: {
      title: route => `dynamic title is ${route.query.param}`
   }
}

And then add a check in the beforeEach hook to set the document.title to the returned value of the title function, in the cases where it is a function:

router.beforeEach((to, from, next) => {
    const { title } = to.meta;
    document.title = typeof title === 'function' ? title(to) : title;
    next();
});
2
votes

As said in the vue router documentation, the to and from objects in navigation guards are both route object, like the $route variable accessible in the component.

Therefore, you can do this :

router.beforeEach((to, from, next) => {
    document.title = to.query.param;
    next();
});