公開日:7/22/2020  更新日:3/26/2022

  • twitter
  • facebook
  • line

【Nuxt.js】動的に生成されたページに個別のmetaタグを設定する方法

はじめに

  • 本ブログはHeadlessCMSのmicroCMSからAPI経由で記事のタイトル、概要、内容を取得しています。
  • 個別のページごとに メタ情報をヘッダーに設定することで、SEO対策になります。
  • Nuxt.js により動的ルーティングされた記事ページに、metaタグをヘッダーへ個別に埋め込んだ方法を備忘録として残します。皆様の参考になれば幸いです。

実際のコード

ブログのホーム画面 ( https://nuxtblog.work ) のmetaタグ情報の設定は、nuxt.config.jshead に設定してます。ちなみに og:∼で書かれるmetaタグはOGPのmetaタグです。OGPとは、「Open Graph Protcol」の略で Facebook やTwitter などの SNS でシェアした際に、設定したWEBページのタイトルやイメージ画像、詳細などを正しく伝えるためのHTML要素です。

nuxt.config.js

・・・
head: {
    title: "新人エンジニアの自習室",
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description',name: 'description',content: 'プログラミングの勉強サイト'},
      { hid: 'og:site_name', property: 'og:site_name', content: '新人エンジニアの自習室' },
      { hid: 'og:type', property: 'og:type', content: 'website' },
      { hid: 'og:url', property: 'og:url', content: 'https://nuxtblog.work' },
      { hid: 'og:title', property: 'og:title', content: '新人エンジニアの自習室' },
      { hid: 'og:description', property: 'og:description', content: 'プログラミングの勉強サイト' },
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }]
  },
・・・

個別ページのmetaタグは, _id.vue に設定します。
microCMS からasyncData メソッドにより取得した json は下記のような構造になっています。

{
    "id": "ブログid",
    "createdAt": "作成日時",
    "updatedAt": "更新日時",
    "publishedAt": "公開日時",
    "title": "記事タイトル",
    "content": "記事内容"
    "description": "記事概要"
}

this.$route.params.id で動的なページidが取得できるので、urlのメタ情報に 'https://nuxtblog.work/blog/'+this.$route.params.id+'/' と設定しています。
後で気づきましたが、json からid を直接とれるので this.item.id でも良かったですね。。。
ちなみに asyncData メソッドの結果は data とマージされますので、このように this でアクセスできています。
これで 記事タイトルや概要を、metaタグ情報として個別に設定することができます。

/blog/_id.vue

・・・
export default {
・・・
  head() {
    return { 
      title: this.item.title ,
      meta: [
        { hid: 'description', name: 'description', content: this.item.description },
        { hid: 'og:type', property: 'og:type', content: 'article' },
        { hid: 'og:title', property: 'og:title', content: this.item.title },
        { hid: 'og:description', property: 'og:description', content: this.item.description },
        { hid: 'og:url', property: 'og:url', content: 'https://nuxtblog.work/blog/'+this.$route.params.id+'/'},
      ],
    }
  },
  ・・・
  async asyncData({ params }) {
    const { data } = await axios.get(
      `https://******.microcms.io/api/v1/blog/${params.id}`,
      {
        headers: { "X-API-KEY": process.env.API_KEY }
      }
    );
    return {
      item: data
    };
  }
};
・・・

参考サイト

1.nuxt.js(v2)でSEOに必要なmeta(OGP)を入れたい
2.API: head プロパティ
3.API: asyncData メソッド

戻る