Vuex 如何处理 api 错误通知? [英] Vuex how to handle api error notification?

查看:68
本文介绍了Vuex 如何处理 api 错误通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两周前我开始使用 Vuex,我意识到 Vuex 非常适合处理应用程序的状态.但是,很难处理 API 调用的错误.当我从服务器获取数据时,我会调度一个动作.当数据成功返回时,当然一切正常.但是当发生错误时,我改变了状态,我不知道如何通过Vuejs组件的状态来检测它以通知用户.谁能给我一些建议?

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?

推荐答案

我通常有以下几个部分:

I typically have the following parts:

  • 用于显示通知的组件,通常是警报或小吃栏或类似物,例如错误通知.我在高层次上使用这个组件,直接在根应用程序组件下面.这取决于您的布局.
  • vuex 中指示错误状态的属性,通常是带有错误代码的错误对象消息,例如错误
  • 存储中的一个突变用于引发设置错误属性的错误,例如raiseError
  • 存储中的一个突变,用于消除清除错误属性的错误,例如dismissError
  • 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

使用这些,您需要:

  • 根据商店中的 error 显示 error-notification:<error-notification v-if="$store.state.error :error="$store.state.error"/>
  • 发生错误时,调用 raiseError 突变(在您的 API 回调中):vm.$store.commit('raiseError', { code: 'ERR_FOO', msg: 'A发生 foo 错误'})
  • error-notification中,当通知关闭时调用dismissError突变.
  • Display error-notification based on the error 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 the dismissError mutation when the notification is closed.

这篇关于Vuex 如何处理 api 错误通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆