【问题标题】:How to get page title in watch:$route for Nuxt/Vue如何在手表中获取页面标题:Nuxt/Vue 的 $route
【发布时间】:2020-04-27 12:33:35
【问题描述】:

基于 Nuxt/Vue 的应用程序在 watch:$route 以及 this.$route 名称、路径中接收,但从不接收元数据。 例如。我有一个页面 Foo 与

export default {
    ...
    head(){
        return{
            title: 'Foo'
        }
    },
    meta: {
        title: 'Foo'
    }
}

在布局中

export default {

    created() {    
        console.log( this.$route );
    }

    watch:{
        $route ({ path, name, meta }){
            console.log( meta );
        }
    }
}

不过,它可以在中间件中使用

export default function ({ store, route }) {
    console.log( route );
}

我可以从中间件填充商店并在应用程序中依赖它,但这对我来说并不是一个好的解决方案。

是否有任何体面的方式来接收带有路由器事件的页面(路由)元数据? 实际上我需要的是内部(SPA)导航事件的页面标题。

【问题讨论】:

  • 也许title: this.$route.meta.title工作
  • 不,this.$route.meta 是空的
  • 这个问题还是没有答案吗?我尝试了其他一些方法,但仅设置页面标题似乎太多了...

标签: vue.js nuxt.js vue-router


【解决方案1】:

Nuxt 有一个名为vue-meta 的插件,默认安装。它是 Vue.js 的 HTML 元数据管理器。

阅读guide,因为使用它非常有帮助,并允许您遵循有关 HTML 元的最佳实践,例如当前页面标题,但基本上您可以使用以下内容:

// in the layout root component, use a computed like this to display the page title:
export default {
  computed: {
    title(ctx) {
      return ctx.$root.$meta().refresh().metaInfo.titleChunk
    },
  }
}
// in each page component, set the page title, using `vue-meta` conventions:
export default {
  head() {
    return {
      title: 'Dashboard',
    }
  },
}

【讨论】:

  • Nuxt.js 使用 vue-meta 来更新应用程序的文档头和元属性。 vue-meta.nuxtjs.org/api/#meta-resume
  • 虽然上述解决方案有效,但有时我会遇到 SSR 错误,因为 refresh() 需要访问 DOM。我不知道为什么这是正常行为,但 Nuxt 在 SSR 期间评估计算值(或似乎)。我自己对与您类似的问题的解决方案是使用 Nuxt 事件总线来更新模板标题:在页面组件 mounted 上使用 this.$nuxt.emit 来表示新标题,在模板组件 created 上使用 this.$nuxt.on 来设置页面标题绑定的本地数据。
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多