【问题标题】:Nuxt: Head function not working for title or meta tagsNuxt:标题功能不适用于标题或元标记
【发布时间】:2020-01-20 15:10:59
【问题描述】:

我有一个用 Nuxt 构建的网页,对于不同的页面,我希望在头部有不同的标题和不同的元描述。我该怎么做?

我在 Nuxt 文档中找到了 head() 方法,但这似乎对我不起作用。

在我的contact.vue中:

export default class Contact extends Vue {
   head() {
      return {
         title: 'Contact page',
         meta: [
            { hid: 'description', name: 'description', content: 'This is a contact page' }
         ]
      }
   }
}

在我的 nuxt.config.js 中:

head: {
    title: 'My website',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
}

根据文档,我希望这会生成元标记。但它只显示在 nuxt.config.js 中声明的标题和元描述。我在这里错过了什么?

【问题讨论】:

    标签: html vue.js nuxt.js


    【解决方案1】:

    我想通了。 在组件中,我将 head 方法放在类中。这没有用。当我把它放在组件装饰器中时,像这样:

     @Component({
        head(): object {
          return {
            title: this.$i18n.t('meta.home.title'),
            meta: [
              {
                hid: 'description', 
                name: 'description',
                content: this.$i18n.t('meta.home.description') 
              },   
            ]
          }
        }
      })
      export default class Home extends Vue {
       ...
    }
    

    确实有效。

    一开始我遇到了一个错误

    Object literal may only specify known objects and 'head' does not exist in type 'ComponentOptions'
    

    通过像这样扩展 ComponentOptions 来解决这个问题:

     declare module "vue/types/options" {
        interface ComponentOptions<V extends Vue> {
          head?: etc etc
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多