Last active
April 6, 2018 10:54
-
-
Save fxmaxvl/9353355f352561376812e90cff6a8a8b to your computer and use it in GitHub Desktop.
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
import { createActionHelpers } from 'vuex-loading'; | |
const helpers = createActionHelpers({ moduleName: 'loading' }); | |
helpers.mapActions = actions => { | |
for (let [action, handler] of Object.entries(actions)) { | |
actions[action] = (ctx, ...rest) => { | |
ctx.$loading = { | |
startLoading: actionName => helpers.startLoading(ctx.dispatch, actionName || action), | |
endLoading: actionName => helpers.endLoading(ctx.dispatch, actionName || action), | |
}; | |
return handler(ctx, ...rest); | |
}; | |
} | |
return actions; | |
}; | |
helpers.mapDecoratedActions = actions => { | |
for (let [action, handler] of Object.entries(actions)) { | |
actions[action] = async (ctx, ...rest) => { | |
helpers.startLoading(ctx.dispatch, action); | |
try { | |
return await handler(ctx, ...rest); | |
} finally { | |
helpers.endLoading(ctx.dispatch, action); | |
} | |
}; | |
} | |
return actions; | |
}; | |
// usage with module actions | |
export default { | |
actions: { | |
...helpers.mapActions({ | |
async fetchUsefulData(ctx) { | |
ctx.$loading.startLoading(); // => startAction(ctx.dispatch, 'fetchUsefulData') | |
const data = await fetch(); | |
ctx.commit('someCommit', data); | |
ctx.$loading.endLoading(); // => endAction(ctx.dispatch, 'fetchUsefulData') | |
} | |
}), | |
...helpers.mapDecoratedActions({ | |
async fetchUsefulData(ctx) { // => startAction(ctx.dispatch, 'fetchUsefulData') | |
const data = await fetch(); | |
ctx.commit('someCommit', data); | |
} // => endAction(ctx.dispatch, 'fetchUsefulData') | |
}) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment