0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【microCMS】Nuxt.js用モジュールを使用するときの動的ページの作成

Posted at

はじめに

こんにちは。
こちらの記事では、microCMSのNuxt.js用モジュールを使用した際に、動的ページでデータを反映させる方法を記しています。
誤っている点がございましたらコメントいただけると幸いです。

前提

前回の記事で紹介した、「Nuxt.js用モジュールを使用したAPI通信」を行う前は、axios通信でデータの取得を行なっていました。
ですが、モジュールを使用するにあたり、記述方法が変わって動的ページの作成につまづいたので、今回記事を執筆いたします。

やりたいこと

axios通信では下記のような記述だったので、モジュールを使用する記述に書き変えたい。

pages/_slug.vue
<template>
  <div>
    <pre>{{ sampleData }}</pre>
  </div>
</template>

<script>
export default {
async asyncData({ params, $axios }) {
  const sample = await $axios.get(
    `https://サービス名.microcms.io/api/v1/APIのエンドポイント/${params.slug}`,
    {
      headers: { "X-API-KEY": "APIキーを入力" },
    }
  );
  const sampleData = sample.data;
  return { sampleData };
},
}

実装手順

microCMS公式を参考に進めていきます。
(モジュールのインストール、nuxt.config.jsの設定、.envファイルの作成は、先ほど紹介した前回の記事に記載したので割愛します。)

公式:microCMSのNuxt.js用モジュールを公開しました

1. pagesの設定

下記のようにエンドポイントまで記述します。

pages/_slug.vue
<template>
  <div>
    <pre>{{ sample }}</pre>
  </div>
</template>

<script>
export default {
async asyncData({ $microcms }) {
  const sample = await $microcms.get({
    endpoint: "APIのエンドポイント",
  });
  return { sample };
},
}

2. 動的ページの対応

動的ページなのでasyncDataの引数にparamsをとり、エンドポイントの後ろに${params.slug}を付与することで、動的ページのデータも反映することができます。

参考:ページディレクトリ

pages/_slug.vue
<template>
  <div>
    <pre>{{ sample }}</pre>
  </div>
</template>

<script>
export default {
async asyncData({ params, $microcms }) {
  const sample = await $microcms.get({
    endpoint: `APIのエンドポイント/${params.slug}`,
  });
  return { sample };
},
}

おわりに

ここまでmicroCMSのNuxt.js用モジュールを使用した際に、動的ページでデータを反映させる方法についてまとめました。

以上、最後まで読んでいただきありがとうございました!
よければLGTMを押してくれると嬉しいです!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?