My component is like this :
...
For usability's sake, I'll suggest using a loader which has its own vuex state.
First define where you would need this particular loader:
If your loader is not tightly coupled to any component like in case 1. Then it would make more sens to keep your loader in your main vue file (if you are using vue-cli then App.vue)
Something like so:
With this, you don't have to add loader.vue in every other component file. But first, I'll show you the loader component and store I am using.
{{ loading }}
Please note that I am using font-awesome for the loader.
and here is the store:
import * as NameSpace from '../NameSpace'
// you can also use the namespace: true in your store and eliminate the need of NameSpace.js
const state = {
[NameSpace.LOADER_STATE]: false
}
const getters = {
[NameSpace.GET_LOADER_STATE]: state => {
return state[NameSpace.LOADER_STATE]
}
}
const mutations = {
[NameSpace.MUTATE_LOADER_STATE]: (state, payload) => {
state[NameSpace.LOADER_STATE] = payload
}
}
const actions = {
[NameSpace.LOADER_SHOW_ACTION]: ({ commit }, payload) => {
commit(NameSpace.MUTATE_LOADER_STATE, payload)
}
}
export default {
state,
getters,
mutations,
actions
}
A usage example:
// This is not a .vue file it is a .js file, therefore a different way of using the store.
import Vue from 'vue'
import * as NameSpace from 'src/store/NameSpace'
import loaderState from 'src/store/modules/loader'
/**
* Pass the mutation function to reduce the text length
* This function can now be used in the api calls to start/stop the loader
* as the api starts and finishes.
*/
let loaderSwitch = loaderState.mutations[NameSpace.MUTATE_LOADER_STATE].bind(null, loaderState.state)
login (username, password) {
loaderSwitch(true)
return new Promise((resolve, reject) => {
SomeEndpoint.logIn(username, password, {
success (user) {
loaderSwitch(false)
resolve(user.attributes)
},
error (user, error) {
loaderSwitch(false)
reject(errorHelper(error.code))
}
})
})
Now, irrespective of the component where login is used, the loader component need not be kept there.