[Vuejs]-How to decorate loader methods to use with loading indicator components? (in Vue)

1šŸ‘

Iā€™m not sure how decorating would work with Typescript/Vue, but in one of my projects I simply used a mixin to provide such feature.

The following solution is untested but gives you a general idea on how to use this mixin for keeping track of loading states:

// loading_mixin.js
export default {
    data() {
        return {
            loader: {
                // This object will contain various keys you pass to
                // the `wrap()` function `type` parameter.
            }
        }
    },
    methods: {
        /**
         * @param {Promise} promise
         * @param {String} type
         * @returns {Promise}
         */
        wrap(promise, type) {
            let loaded = this.loader[type] ? this.loader[type].loaded : false;
            this.$set(this.loader, type, {loading: true, loaded: loaded});
            return promise.then((data) => {
                this.$set(this.loader, type, {loading: false, loaded: true});
                return data;
            }).catch((err) => {
                this.$set(this.loader, type, {loading: false, loaded: false});
                throw err;
            });
        },
    }
}

Usage (YourComponent.vue):

<template>
    <div>
        <loading-component :loader="loader.load_data" />
    </div>
</template>
<script>
    import loadingMixin from '...';
    export default {
        mixin: [loadingMixin],
        methods: {
            load() {
                this.wrap(this.loadMyData(1, 2), 'load_data').then((data) => {
                    // Handle success.
                }).catch((err) => {
                    // Handle err.
                })
            },
            loadMyData(a, b) {
                return Promise.resolve(a + b);
            }
        }
}
</script>

I hope this gives you some ideas.

šŸ‘¤Flame

Leave a comment