概要
Vueでローディング画面を作成します。
実装
ローディングのモジュールはいくつかありますが、今回はvue-loadersというモジュールを利用します。
アニメーションの種類が多かったのでこれにしました。
導入方法はこちら
github
今回はmounted()のタイミングでローディングを開始し、mounted()が終わったタイミングでローディングを終了したいと思います。
store
store/loading.js
const state ={
    loading: true, //true:ローディングを表示, false:ローディング非表示
};
const getters ={
    loading: state => state.loading ? state.loading: '',
};
const mutations ={
    setLoading(state,loading){
        state.loading = loading;
    },
};
const actions = {
    async startLoad(context){
        context.commit('setLoading', true);
    },
    async endLoad(context){
        context.commit('setLoading', false);
    } 
};
export default{
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
ローディングが開始したらstartLoadを発火、終わったらendLoadを発火して非表示にします。
template
.vue
<template>
    <div class="new-article">
            <div class="loader-space" v-show="loading">
                <vue-loaders-ball-beat color="#FFF" class="loader"></vue-loaders-ball-beat>
            </div>
            <div class="contents" v-show="!loading">
            <!--ローディング後に表示したいコンテンツ-->
            </div>
        </div>
    
</template>
<script>
export default {
    computed: {
        loading(){
            return this.$store.getters["loading/loading"];
        },
    },
    methods: {
        async getPost() {
            const post = this.$store.getters["newtimeline/post"];
            if(!post){
                await this.$store.dispatch('newtimeline/getPost');
            }
        },
    },
    mounted() {
        console.log('mounted start');
        this.$store.dispatch('loading/startLoad')               //ローディング開始をする loading = true;
            .then(()=>this.getPost())                           //getPost()メソッドを開始
            .then(()=>this.$store.dispatch('loading/endLoad')); //ローディング終了 loading = false;
    },
}
</script>
非同期処理で動かさないとendLoad()の方が先に走ってしまうので、非同期で実装しましょう。
最後に
割と簡単に実装することができました。
面白いアニメーションもあり、使ってて楽しかったです。
