美文网首页
vue的axios拦截器使用

vue的axios拦截器使用

作者: 紫气楠楠 | 来源:发表于2019-12-03 12:28 被阅读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=>{
            
          })
        }
    

    相关文章

      网友评论

          本文标题:vue的axios拦截器使用

          本文链接:https://www.haomeiwen.com/subject/ejzimctx.html