LoginSignup
79
71

More than 5 years have passed since last update.

Vue.jsでAPI通信中にloading表示をする

Posted at

はじめに

APIからのレスポンスを受け取るまではloading表示をしておいて、結果を受け取ってから内容表示するようにします。

Js

index.js
var app = new Vue({
    el: '#app',
    data: {
        results: [],
        loading: true
    },
    components: {
        'item-component': ItemComponent
    },
    mounted () {
        axios
            .get("api.php")
            .then(response => {
                this.results = response.data;
                this.loading = false;
            })
    }
});

loading のプロパティを用意し、初期状態ではtrueにしておきます。
axiosでのAPI通信が終わったタイミングでfalseにします。

(好みに応じて)loading表示の素材

必須では無いのですが、テキスト表示だけだと寂しいので、下記サイトから気に入ったloading表示を loading.css としてローカルに保存しておきます。

Single Element CSS Spinners

HTML

下記のように v-show 属性に上記のloadingを指定し、loading表示部分と結果表示部分が状況に応じて排他的に表示されるようにします。

index.html
<div v-show="loading" class="loader">Now loading...</div>
<div v-show="!loading" class="itemContainer">
    <item-component
        v-for="(result, index) in results" :key="index"
        v-bind:id="result.id"
        v-bind:name="result.name"
        v-bind:value="result.value"
    >
    </item-component>
</div>
79
71
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
79
71