Pass var to vue router in meta

戏子无情 提交于 2020-02-06 11:23:37

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/54205148/pass-var-to-vue-router-in-meta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!