vue的axios拦截器使用
2019-12-03 本文已影响0人
紫气楠楠
axios拦截器
下载并使用axios后可以对全局进行拦截器设置。拦截器在发送请求前或响应返回时做一些特殊的处理。
下面是一个为axios添加请求loading的例子:
添加请求拦截器
//定义一个请求拦截器
axios.interceptors.request.use(function(config){
Vue.$vux.loading.show(); //在请求发出之前进行一些操作
return config
},function (error) {
// 对请求错误做些什么
// return Promise.reject(error)
});
添加响应拦截器
//定义一个响应拦截器
axios.interceptors.response.use(function(config){
Vue.$vux.loading.hide();;//在这里对返回的数据进行处理
return config
},function (error) {
// 对请求错误做些什么
// return Promise.reject(error)
});
移除拦截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
为axios实例添加拦截器
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
某一个函数不希望受到全局拦截器的影响
解决方法:在函数内从新添加一个拦截器
如下:为请求函数添加一个新的拦截器使之不受全局拦截器影响
const $ajax = this.$http.create()
例:下面函数不受全局拦截器影响
pollopenid(){
const $ajax = this.$http.create()
$ajax({
method:'post',
url:'',
data:{
}
}).then(res=>{
})
}