【问题标题】:How to manage page titles dynamically in Vuejs?如何在 Vuejs 中动态管理页面标题?
【发布时间】:2019-06-13 00:07:36
【问题描述】:

我构建了一个应用程序。我有一个带有页面标题的标题。目前,我使用 view-router 来定义我的标题。

{
    path: '/events',
    name: 'events',
    component: Events,
    meta: {
        title: 'Liste des événements'
    }
}

在我的刀片视图中,在我的 header.blade.php 中,我这样做是为了显示标题

 <h2 class="header__title title-header">
    @{{ $route.meta.title }}
 </h2>

它可以工作,但是当我有动态数据时,它必然不起作用。例如,当我发布帖子时,如何才能获得我的头衔?

    {
    path: '/events/:id',
    component: Event,
    name: 'Event',
    meta: {
        title: 'my dynamic title',
        page: 'event',
    },

如何恢复帖子页面的标题?我的帖子中有帖子的名称,但我无法从标题中访问它...

我无权访问其他组件。这些是来自 element-ui 的组件。

提前谢谢你

【问题讨论】:

  • 一般我都是在fetch或者post之后用data来设置title的,试试看
  • @Sadeghbayan 有什么例子吗?

标签: laravel vue.js


【解决方案1】:

在你的路由器中,在export default router之前你可以添加

router.beforeEach((toRoute, fromRoute, next) => {
  window.document.title = toRoute.meta && toRoute.meta.title ? toRoute.meta.title : 'Home';

  next();
})

这将读取元标题(如果存在)并更新页面标题。

或者你可以这样添加

const router = new Router({
  beforeEach(toRoute, fromRoute, next) {
    window.document.title = toRoute.meta && toRoute.meta.title ? toRoute.meta.title : 'Home';

    next();
  },
  routes: [
    ...
  ]
})

不要忘记将默认标题值从 Home 更改为其他值 - 可能是您的项目名称

【讨论】:

  • 感谢@ljubadr,它就像一个魅力。但是,例如,当我访问文章的页面时,我该如何处理帖子的数据?谢谢
  • 在完成获取帖子的 ajax 调用后,您需要抓取文章的磁贴并设置window.document.title = response.data.title。您能否为您的 ajax 调用提供代码以获取帖子以及应将哪个帖子字段设置为标题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2019-09-05
相关资源
最近更新 更多