[英]Pass a parameter to Vue router meta title
我正在尝试为 Vue 路线创建动态标题。 似乎我找不到将参数传递给元标题的方法。 我需要它,因为我有一个VueHeader
组件,它从路由元标题呈现标题。 这是我的代码:
{
path: '/case/:id',
name: 'edit-case',
component: VueEditCase,
meta: {
title: 'Edit case ' + $route.params.id,
},
},
但是,我收到一个错误Uncaught ReferenceError: $route is not defined
。 如果我有title: 'Edit case ' + this.$route.params.id
或title: 'Edit case ' + route.params.id
或title: 'Edit case ' + this.route.params.id
。 我也试过title: 'Edit case ' + ':id'
等。
我在互联网上找不到任何答案,所以我在这里寻求你们的帮助,伙计们。 有人遇到过类似的问题并解决了吗?
我认为这可以帮助你,把它写在文件的mounted hook
里
mounted() {
document.title = "Edit Case " + this.$route.params.id
}
让我知道这对你是否像对我一样有效
我曾经试图完成同样的事情,但不幸的是,我认为这是不可能的。 正如这个人在 GitHub 上所说的,路由器的元是故意静态的。
如果您想使文档的<title>
标签动态化,我建议您尝试Vue-Meta 。 我真的很喜欢这个插件,并在每个 Vue SPA 项目中使用它。
可以像下面这样设置元值,
this.$route.meta.title = "Your title";
在您的情况下,您可以从任何父组件观察路由更改并设置元值。
watch: {
// watching the route
'$route': function () {
// if params and id
if (this.$route.params && this.$route.params.id) {
this.$route.meta.title = "Your title " + this.$route.params.id;
}
}
}
如果您使用VUE META ,请按照文档在视图的每个组件上设置标题,因此,在带有 url 参数的组件中,添加此代码
<script>
export default {
name: "MyComponent",
metaInfo() {
return {
title: () => {
return "My title with params " + this.$route.params.my_param;
}
};
}
};
</script>
metaInfo()
是 vue meta 的一个函数,你可以使用路由参数在头上设置任何标签。
试试this.$route
或
console.log(window.location)
在那里,看看如何从那里检索 id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.