这是我所做的,我不确定它的正确:
//store
async addUser({commit}) {
try {
const {data} = await apiService.addUser()
commit('SET_USER', data)
commit('SET_NOTIFICATION', {type:'success', message: 'user successfuly created'})
} catch (error) {
commit('SET_NOTIFICATION', {type:'error', message:error})
}
}
SET_USER(state, user) {
state.users.push(user)
}
//my component:
async addUser() {
this.isLoading = true
await this.$store.dispatch('updatePatient', this.form)
this.isLoading = false
}
合法吗?
有时我认为我的组件内需要更多逻辑,具体取决于成功或拒绝API请求。我应该把所有逻辑都放在我的行动中吗?就像我目前那样?
也许我应该为每个动作添加一个状态状态,例如:
state {
users: []
postUserSuccess: null
postUserError: false
updateUserSuccess: null
updateUserError: false
// ...
}
并用映射到商店的计算属性在组件中做我想做的事?
您怎么看?
我不知道这是最好的做法,但我让组件进行了例外处理。该方法具有其优点(您不必使用错误管理污染状态)和缺点(您必须重复每个操作调用的错误管理代码)。
- 所有服务呼叫都将在操作中进行
- 状态仅在突变中设置。
- 所有服务呼叫都将通过解决方案(将加载在该州加载的数据)和拒绝(以下消息错误)返回承诺。
- 如果有自定义错误,将会有一个拦截器拒绝响应(如果响应具有错误prop拒绝响应并将其作为错误提示发送,则可以在此处放置,现在您不必解构动作中的响应)。
我将为您提供一个简单的示例(我使用Axios,您可以学习如何使用所使用的库)。
Vuex中的动作是异步的。因此,您无需尝试/捕捉它们。
apiservice-添加用户
const addUser = () => {
return new Promise((resolve, reject) => {
axios
.post(url, user)
.then(response => resolve(response.data))
.catch(error => reject(error));
});
};
商店
async addUser({commit}) {
const data = await apiService.addUser();
commit('SET_USER', data);
return data;
}
如果解决了apiService.addUser
中的承诺,则如果被拒绝Axios将返回承诺,您将在调用操作的组件中捕获错误。
组件
async addUser() {
this.isLoading = true;
try {
await this.$store.dispatch('updatePatient', this.form);
} catch (error) {
// here goes the code to display the error or do x if there is an error,
// sometimes I store an errors array in the data of the component other times I do x logic
}
this.isLoading = false;
}
状态既然您不需要将这些错误存储在那里,那么您的状态将变得更加干净。
state {
users: []
}