首页 > 解决方案 > 如何在手表中获取页面标题:Nuxt/Vue 的 $route

问题描述

基于 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)导航事件的页面标题。

标签: vue.jsnuxt.jsvue-router

解决方案


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

阅读该指南,因为使用它非常有帮助,并允许您遵循有关 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',
    }
  },
}

推荐阅读