Skip to content

Instantly share code, notes, and snippets.

@lazerg
Last active January 22, 2022 20:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazerg/e81f20ea83944f927731be24a67b010f to your computer and use it in GitHub Desktop.
Save lazerg/e81f20ea83944f927731be24a67b010f to your computer and use it in GitHub Desktop.
Mixin for vuejs 2 to handle loading statuses.
const DEFAULT = null;
const IS_LOADING = 0;
const IS_LOADED = 1;
const IS_FAILED = 2;
export default {
data: {
loading: DEFAULT,
},
methods: {
/**
* Mark status as loading
*
* @return void
*/
loadingStart () {
this.loading = IS_LOADING;
},
/**
* Mark status as loaded
*
* @return void
*/
loadingSuccess () {
this.loading = IS_LOADED;
},
/**
* Mark status as failed
*
* @return void
*/
loadingFail () {
this.loading = IS_FAILED;
},
/**
* Start requesting to endpoint
*
* @param {Function} callback
* @returns {Promise<void>}
*/
async startLoading (callback) {
try {
this.loadingStart();
await callback();
this.loadingSuccess();
} catch (error) {
this.loadingFail();
throw error;
}
}
},
computed: {
/**
* Check if loading is in progress
*
* @returns {boolean}
*/
isLoading () {
return this.loading === IS_LOADING;
},
/**
* Check if loading is successful
*
* @returns {boolean}
*/
isLoaded () {
return this.loading === IS_LOADED;
},
/**
* Check if loading is failed
*
* @returns {boolean}
*/
isFailed () {
return this.loading === IS_FAILED;
},
},
};
@lazerg
Copy link
Author

lazerg commented Jan 22, 2022

With this mixin, you can easily handle loading statuses while requesting in some endpoint.

#1 You can change statuses manually:

this.loadingStart();
axios.get('https://jsonplaceholder.typicode.com/todoss').then(response => {
    this.loadingSuccess();
    this.response = response.data;
}).catch(error => {
    this.loadingFail();
});

#2 You can use built-in helper startLoading (Recommended)

this.startLoading(async () => {
    this.response = await axios.get('https://jsonplaceholder.typicode.com/todoss');
});

And in vue template, you can handle response easily with helper conditions

<template>
    <div v-if="isFailed">
        Something wrong with server
    </div>

    <div v-else-if="isLoaded">
        <!-- Show content in table for example -->
    </div>

    <div v-else>
        <!-- Show some loading indicator -->
    </div>
</template>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment