Last active
January 22, 2022 20:21
-
-
Save lazerg/e81f20ea83944f927731be24a67b010f to your computer and use it in GitHub Desktop.
Mixin for vuejs 2 to handle loading statuses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}, | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With this mixin, you can easily handle loading statuses while requesting in some endpoint.
#1 You can change statuses manually:
#2 You can use built-in helper
startLoading
(Recommended)And in vue template, you can handle response easily with helper conditions