11
8

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 5 years have passed since last update.

Vue.jsからaxiosで適当なjsonデータを取得して表示する

Last updated at Posted at 2018-07-25

Vue.jsの入門としてまずは vue-cli を使わずにjsだけで色々と試してみたいなと思った今日この頃。

jsonデータ

MyJsonを使って適当なJsonを返してくれるURLを作成する。
MyJsonはCORSに対応しているのでaxiosから直接アクセスしても大丈夫。

Webサーバー

Dockerでhttpdの公式イメージから起動。

docker run --name httpd -d -p 8080:80 -v ${pwd}:/usr/local/apache2/htdocs/ httpd

マウントしたディレクトリに下記のファイルを配置する。

HTML

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="index.css">
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <div class="itemContainer">
                <div v-for="result in results" class="item">
                    <div>ID: {{ result.id }}</div>
                    <div>名前: {{ result.name }}</div>
                    <div>値: {{ result.value }}</div>
                </div>
            </div>
        </div>
        <script src="index.js"></script>
    </body>
</html>

CSS

html, body {
    margin: 5px;
    padding: 0;
}

.itemContainer{
    display: flex;
}

.item {
    border: solid;
    margin: 5px;
}

js

var app = new Vue({ 
    el: '#app',
    data: {
        results: []
    },
    mounted () {
        axios
            .get("https://api.myjson.com/bins/1h6kbm")
            .then(response => {this.results = response})
    }
});

ブラウザで表示

http://localhost:8080/ にアクセス

03.png
11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?