将 var 传递给 meta 中的 vue 路由器 [英] Pass var to vue router in meta
问题描述
我有一个用 vue-router 创建的路由.
I have a route created with vue-router.
{
path: '/events/:id',
component: Event,
name: 'Event',
meta: {
title: 'Design Web'
}
},
在meta"中,我给它命名我的页面.
In "meta", I give it the name of my page.
我可以通过这样做来调用我的页面的标题:$route.meta.title
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
}
怎么办?
谢谢
推荐答案
如果你将 title 属性定义为一个函数是可能的:
It is possible if you define the title attribute as a function :
{
meta: { title: route => { /* return custom title based on route, store or anything */ } }
}
和
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(您需要检查内部 iframe 以查看标题更改).
Codepen: https://codepen.io/anon/pen/roRmdo?editors=1111 (you need to inspect inner iframe to see the title change).
或者创建一个指令:
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>
组件:
export default {
data(){
return {
title: 'This will be the title'
}
}
}
来源:https://github.com/vuejs/vue-router/issues/914
这篇关于将 var 传递给 meta 中的 vue 路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!