LoginSignup
13

More than 5 years have passed since last update.

Vue.jsとaxiosを使用してWordpressの記事一覧を取得する

Posted at

はじめに

企業サイトなどは通常静的に作成することが多いですが、
新着情報やリリースノートなどはWordpressで運用することが多いです。

トップページにその一覧を表示する際は、PHPで呼びだすことが一般でしたが、
Wordpress 4.7 からWP REST APIが標準装備されました。

しかしPHPで書くとWordpressの余分なリクエストを受けてしまい、レスポンスが低下します。
WP REST APIを使用してレスポンスをあげつつ一覧を呼びだしてみたいと思ったので試してみました。

使用したライブラリ

作成工程

コンポーネントの作成

Wordpressのカスタム投稿などを駆使して複数のブログコンテンツを作成する案件がほとんどです。
そのためコンポーネントを作成して、再利用可能なコードを用意します。

今回エラー時のハンドリングを記述していませんので、実運用の際はその処理を追加する必要があります。

main.js
Vue.component('testAxios', {
  props: ['theUrl'],
  data () {
    return {
      info: '',
    }
  },
  mounted () {
    axios
      .get(this.theUrl)
      .then(response => (this.info = response.data))
  },
  template: `<article>
    <section v-for="item in info">
      <h2>{{ item.title.rendered }}</h2>
      <p v-html="item.excerpt.rendered"></p>
      <time>{{ item.date.slice(0, 10) }}</time>
    </section>
    </article>`,
});

呼びだすAPIのURLを定義

呼びだすAPIのURLについてはWP REST APIのサイトをご覧ください。

main.js
new Vue({
  el: '#app',
  data: function() {
    return {
      theUrlAlpha: 'http://example.com/wp-json/wp/v2/posts?per_page=3',
      theUrlBravo: 'http://example.com/wp-json/wp/v2/posts?per_page=6',
    }
  },
});

HTML側の記述

コンポーネントを記述して、そのコンポーネントに表示させたいAPIを紐付けます。

index.html
<div id="app">
  <test-axios :the-url='theUrlAlpha'></test-axios>
  <hr>
  <test-axios :the-url='theUrlBravo'></test-axios>
</div>

まとめ

無事に呼びだすことができました。
これで純粋な静的ページとさせながらも、動的に記事一覧を取得させられます。

JavaScriptに不慣れなため不備が見受けられるかもしれません。
不備や改善点がございましたらご指摘いただけますと幸いです。

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
13