0
1

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.

asyncData 使う時、使わない時のコード比較【おまけ】

Posted at

この記事は
Nuxt.js × Netlify × MicroCMSでJamstackブログを公開しよう【完全図解】のおまけです。

Axiosで記事を取得したのですが、他の記述もできます。
参考までに記載しておきますのでお試しください。

パターンA

news.vue
<script>
import axios from "axios";
export default {
data() {
    return {
      news: null
    };
  },
  methods: {
    fetchNews() {
      axios
        .get("https://あなたのURL/api/v1/news?limit=60", {
          headers: { "X-API-KEY": "あなたのAPIキー" }
        })
        .then(res => {
          // console.log(res.data);
          this.news = res.data.contents;
        })
        .catch(e => {
          console.log(e);
        });
    }
  },
  mounted() {
    this.fetchNews();
  }
};
</script>

##パターンB

blog.vue
<script>
import axios from "axios";
export default {
  async asyncData() {
    const { data } = await axios.get(
      "https://あなたのドメインID.microcms.io/api/v1/blog",
      {
        headers: { "X-API-KEY": "あなたのAPIキー" }
      }
    );
    return data;
  }
};
</script>

Bの方がすっきりかけますね。ただし、thisを使えない、データのアクセス向きで格納向きではないなどがありますので、気になった方は調べてみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?