axios-add-loading
本库通过axios
的interceptors帮助你设置ajax请求中的loading
安装
npm i -S axios-add-loading
语法
createAddLoadingInterceptor(
axios: AxiosInstance,
options: AxiosAddLoadingOptions
)
参数
axios
: axios实例
options
: object类型参考参数说明
如何使用
import createAddLoadingInterceptor from 'axios-add-loading'
import axios from 'axios'
const instance = axios.create()
const options = {
showLoading: true,
delEmpty: true,
openLoading: () => { },
closeLoading: () => { },
isResOk: res => { },
onResNotOk: res => { },
onResError: e => { }
}
createAddLoadingInterceptor(instance, options)
instance({
method: 'get',
url: 'dir/xxx',
params: { foo: 'bar' },
showLoading: false,
delEmpty: false,
})
参数说明
delEmpty: boolean
是否删除 get
请求中 params 中为空的字段 xxx/dir?a=&b=3
=> xxx/dir?b=3
delEmpty: true
showLoading: boolean
是否显示loading,需结合openLoading
和closeLoading
使用
showLoading: true
openLoading: () => void
显示 loading 的方法, 拦截器发起请求前触发
openLoading: () => { }
closeLoading: () => void
隐藏 loading 的方法, 拦截器完成请求触发
closeLoading: () => { }
isResOk: res => boolean
大多数情况下response-schema只需要用到data,本方法主要过滤response-schema参数res为其中的data,定义规则确定那些返回内容是符合规则
的,如果未设置,拦截器将会返回response-schema
isResOk: res => res.code === 200
onResNotOk: res => void
只有设置了 isResOk
才会生效,对不符合isResOk的请求进行处理
onResNotOk: res => {
if (res.code === 401) {
gotoLogin()
}
}
onResError: e => void
e为handling-errors, 对于请求异常的错误处理
onResError: e => {
if (e.response.status === 401) {
gotoLogin()
}
}