Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass var to vue router in meta

I have a route created with vue-router.

{
    path: '/events/:id',
    component: Event,
    name: 'Event',
    meta: {
        title: 'Design Web'
    }
},

In "meta", I give it the name of my page.

I can call the title of my page by doing this: $route.meta.title

But now, I'm facing a problem. In the title of my page, I would like to pass a variable (the name of my event).

meta: {
  title: $nameOfEvent
}

How to do ?

Thank you

like image 206
Jeremy Avatar asked Jan 02 '23 10:01

Jeremy


1 Answers

It is possible if you define the title attribute as a function :

{
  meta: { title: route => { /* return custom title based on route, store or anything */ } }
}

and

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

Codepen: https://codepen.io/anon/pen/roRmdo?editors=1111 (you need to inspect inner iframe to see the title change).

or create a directive:

Vue.directive('title', {
  inserted: (el, binding) => document.title = binding.value,
  update: (el, binding) => document.title = binding.value
})

Then use that directive on the router-view component:

<router-view v-title="title" ></router-view>

Component:

export default {
  data(){
    return {
      title: 'This will be the title'
    }
  }
}

Source: https://github.com/vuejs/vue-router/issues/914

like image 185
Beniamin H Avatar answered Jan 11 '23 22:01

Beniamin H