LoginSignup
22
12

More than 3 years have passed since last update.

Nuxt.js で動的にOGPを表示させたい

Posted at

要件

ディレクトリ構造が以下のようになっている時に、item/_idページのOGPでそのアイテムの名前とか画像とかを動的に表示させたい!
(item/1, 2, ... で表示させるものを変える)

-item
|-_id.vue
|-new.vue
|...

OGP実装

基本

基本的な実装は[この記事]を参考にしてください。どちゃくそわかりやすく書かれています。(https://qiita.com/amishiro/items/b7260116b282d2cf2756)

本題

上の記事を読んでいただいて

  • nuxt.config.jsにデフォルトのogp設定済み

のような環境になってからここを読み始めてください。

恐らく、item/_id.vue内でitem情報をapi等から取得してきていると思いますが、そのデータを用いてmetaタグの中身を書いていきます。

_id.vueに組み込むmixinを以下のように書きます。

ogpMixin.js
export default {
  data() {
    return {
      meta: {
        title: "",
        description: "",
        type: "",
        url: "",
        image: ""
      },
      // ベースとなるurl。自分の環境に合わせてください。
      base: "https://example.net"
    };
  },
  head() {
    // 相対パスを取得。例えば'/item/1'とか
    const path = this.$route.path;

    ----------------------------------------
    // 点線内は書かない
    // 組込先(item/_id)に次のようなデータがあるという設定を示す
    item: {
      name: '~~~',
      explanation: '~~~',
      image: '~~~'
    },
    ----------------------------------------

    // ここでmetaの中身を更新
    this.meta.title = this.item.name;
    this.meta.description = this.item.explanation;
    this.meta.type = "article";
    this.meta.url = this.base + path;
    this.meta.image = this.item.image;

    // ここから先でmetaタグを書いていく
    return {
      title: this.meta.title,
      meta: [
        { hid: "description", name: "description", content: this.meta.description},
        { hid: "og:description", property: "og:description", content: this.meta.description},
        { hid: "og:title", property: "og:title", content: this.meta.title },
        { hid: "og:type", property: "og:type", content: this.meta.type },
        { hid: "og:url", property: "og:url", content: this.meta.url },
        { hid: "og:image", property: "og:image", content: this.meta.image },
        { name: "twitter:title", content: this.meta.title }
      ]
    };
  }
};

ポイントはhead()内で処理を行うことです。
ogpで探しにくるボットはクライアントサイドの処理を待ってくれないので、クライアントサイドでのみ行われるmouted()等で書くとうまく実行されません(ページのmetaタグは表示されるが、ogpが表示されない)

もし参考になったらいいね!お願いします!!

22
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
12