LoginSignup
47
43

More than 5 years have passed since last update.

Vue.js + axios で Qiita API v2 を叩いて投稿を取得する

Last updated at Posted at 2017-08-24

検証環境

  • Vue.js (v2.4.2)
  • axios (v0.16.2)

gulpでトランスパイラを使用した状態で検証しています。

公式リンク

axios のインストール

npm install axios --save

作成画面

読み込みボタン押下でリンク付きの投稿タイトルとタグを取得します。

sc.png

ソースコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Qiita Posts | Vue.js + axios test</title>
    <link rel="stylesheet" href="/css/main.css">
    <script src="https://unpkg.com/vue"></script>
    <script src="/js/main.js" charset="utf-8" async></script>
</head>
<body>
    <section id="qiita-posts">
        <h1>Qiita Posts</h1>
        <button v-on:click="request">読み込み</button>

        <hr>

        <ul>
            <li v-for="post in posts" >
                <span class="tag" v-for="tag in post['tags']">{{ tag['name'] }}</span>

                <a v-bind:href="post['url']" target="_blank" rel="noopener noreferrer">
                    <div>{{ post['title'] }}</div>
                </a>
            </li>
        </ul>
    </section>
</body>
</html>
main.scss
body {
    padding: 0 10px;
}

#qiita-posts {
    h1 {
        margin-bottom: 20px;
        font-size: 1.2rem;
        font-weight: bold;
    }

    button {
        margin-bottom: 10px;
        padding: 4px 10px;
        color: #fff;
        font-size: 0.75rem;
        background: #325d7c;
        border: none;
        border-radius: 2px;
        box-shadow: 0 4px 0 darken( #325d7c, 4% );
        cursor: pointer;
    }

    li {
        margin-bottom: 15px;
        line-height: 1.5;

        .tag {
            display: inline-block;
            margin: 0 1px 6px;
            padding: 2px 6px;
            color: #fff;
            font-size: 0.75rem;
            background: #7daaca;
        }

        a {
            color: darken( #7daaca, 24% );
        }
    }
}
main.js
'use strict';

import axios from 'axios';

let vm = new Vue( {
    el: '#qiita-posts',
    data: {
        posts: void(0),
    },
    methods: {
        request: () => {
            axios.get( 'https://qiita.com/api/v2/users/[QiitaユーザID]/items' )
                .then( ( res ) => {
                    vm.posts = res.data;
                } )
                .catch( ( res ) => {
                    console.error( res );
                } );
        }
    },
} );

取得されるデータ構造の詳細は、Qiita API v2ドキュメント - 投稿 を参照してください。

おわりに

Vue.jsの勉強ついでに実装してみましたが、axiosと組み合わせるとAjax周りの処理が簡単すぎて驚くばかりです。

47
43
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
47
43