LoginSignup
20
14

More than 5 years have passed since last update.

Vue.js + Wordpress REST API

Last updated at Posted at 2017-05-18

WordpressのRESTからJSONを読み込んでリストを出力するまでが割とサクッとかけたので丸ごと貼り付け。
ajaxはaxios利用。

html/css/js丸ごとコード

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Vue + WP-Rest</title>
  <style>
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-to{
    opacity: 0;
  }
  </style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.1/axios.js"></script>
  <script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <posts></posts>
  </div>
  <script>
    Vue.component('posts', {
      data: function(){
        return {
          page: null,
          posts: [],  // placeholder、リアクティブにするために必須とのこと。
        }
      },

      // watchだけで済ませてるのでマウント後でpage変更している。
      mounted: function(){
        this.page = 1;
      },

      // 非同期など複雑になってくる場合computedよりwatchの方が向いてるケースがあるとのこと。
      watch: {
        page: function(newpage){
          var _component = this;  // スマートじゃないやつ
          // axios利用
          axios.get(
            'http://exsample.com/wp-json/wp/v2/posts?page=' + _component.page,
            {sending: false}
          )
          .then(function(response){
            // 普通に$setすると追加せず全記事が置き換わる。
            _component.posts = _component.posts.concat(response.data);
            return this;
          });
        }
      },
      methods: {
        // リンククリックの処理
        onclick: function(e){
          console.log(e.title.rendered)
        },

        // 追加ローディングボタンクリック時の処理、page数を増やすだけ。
        // 全てロード仕切った場合はpageは増えるがpostsが増えないので
        // watchが動かず特にエラーもなく何も起きないがdisabled処理など別途必要。
        loadMore: function(){
          this.page++;
        }
      },
      // 追加時フェードさせるためにtransition-groupとcss用意
      template: [
        '<div>',
          '<transition-group name="fade" tag="ul">',
            '<li v-for="post in posts" v-bind:key="post.title.rendered">',
              '<a :href="post.slug" @click.prevent="onclick(post)">{{post.title.rendered}}</a>',
            '</li>',
          '</transition-group>',
          '<button @click="loadMore">load more</button>',
        '</div>'
      ].join('\n')
    });

    var vm = new Vue({
      el: '#app',
    })
  </script>
</body>
</html>

という具合にシンプルになりました。

表示結果

スクリーンショット 2017-05-19 4.06.03.png

20
14
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
20
14