问题
I started working with Vuex 2 weeks ago and I realized that Vuex is very good to handle the state of the app. But, it is difficult to handle the error of API calls. When I get data from the server, I dispatch an action. When data is successfully returned, of course, everything is fine. But when an error happens, I change state, I don't know how to detect it through the state from Vuejs components to notify to the user. Could anyone give me some advice?
回答1:
I typically have the following parts:
- A component for displaying the notification, typically an alert or a snackbar or similar, e.g.
error-notification
. I use this component on a high level, directly below the root app component. This depends on your layout. - A property in vuex indicating the error state, typically an error object w/ error code & message, e.g.
error
- One mutation in the store for raising an error setting the error property, e.g.
raiseError
- One mutation in the store for dismissing an error clearing the error property, e.g.
dismissError
Using these, you need to:
- Display
error-notification
based on theerror
in the store:<error-notification v-if="$store.state.error :error="$store.state.error"/>
- When an error occurs, call
raiseError
mutation (in your API callback):vm.$store.commit('raiseError', { code: 'ERR_FOO', msg: 'A foo error ocurred'})
- In
error-notification
, call thedismissError
mutation when the notification is closed.
回答2:
You can also return a promise in your action so that if you call it from component you can catch the error there and display a notification as needed:
in your store:
//action
const fetch = (context) => {
return api.fetchTodos() //api here return promise. You can also do new Promise(...)
.then((response) => {
context.commit('SET_TODOS', response);
})
};
in vue component:
this.$store.dispatch('todos/fetch', modifiedTodo)
.catch(error => {
//show notification
})
来源:https://stackoverflow.com/questions/52988261/vuex-how-to-handle-api-error-notification