R1p*_*das 3 error-handling vue.js vuex
这是我所做的,我不确定它是否正确:
//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)
}
Run Code Online (Sandbox Code Playgroud)
//my component:
async addUser() {
this.isLoading = true
await this.$store.dispatch('updatePatient', this.form)
this.isLoading = false
}
Run Code Online (Sandbox Code Playgroud)
合法吗?
有时我认为我的组件中需要更多逻辑,具体取决于成功或拒绝的 api 请求。我应该把所有的逻辑都放在我的行动中吗?就像我现在做的那样?
也许我应该为每个动作添加一个状态状态,例如:
state {
users: []
postUserSuccess: null
postUserError: false
updateUserSuccess: null
updateUserError: false
// ...
}
Run Code Online (Sandbox Code Playgroud)
并使用映射到商店的计算属性在组件中执行我想要的操作?
你怎么认为 ?
我不知道这是否是最佳实践,但我让组件进行异常处理。该方法有其优点(您不必使用错误管理污染状态)和缺点(您必须为每个操作调用重复错误管理代码)。
我会给你一个简化的例子(我使用 axios,你可以学习如何使用你使用的库来做到这一点)。
Vuex 中的动作是异步的。所以你不需要尝试/抓住它们。
ApiService - 添加用户
const addUser = () => {
return new Promise((resolve, reject) => {
axios
.post(url, user)
.then(response => resolve(response.data))
.catch(error => reject(error));
});
};
Run Code Online (Sandbox Code Playgroud)
店铺
async addUser({commit}) {
const data = await apiService.addUser();
commit('SET_USER', data);
return data;
}
Run Code Online (Sandbox Code Playgroud)
如果承诺中的承诺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;
}
Run Code Online (Sandbox Code Playgroud)
状态 您的状态将是清洁现在你不需要保存这些错误在那里。
state {
users: []
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3107 次 |
| 最近记录: |