Axios的基本使用

axios使用

作为全局对象来使用,不像vue-resource挂在在Vue实例上。

引入

  • <script src="..../axios.min.js"></script>
  • npm install axios --save

提供API

  • get
    axios.get('../package.json',{
        params:{        //用于get请求
            userId:"999"
        },
        headers{        //注册请求头 
            token:"jack"
        },
        before:function(){
            console.log("before init.")
        }
    }).then(res=>{
        this.mas = res.data   
    }).catch(err=>{
        console.log("error init"+ err);
    })
  • post
    axios.post('../package.json',{
        userId:"888"        //注意:第二个参数用于传递参数
    },{             
        headers:{           //第三个参数才是option选项
            token:"tom"
        }
    }).then(res=>{
        this.msg = res.data
    })
  • 全局配置
    axios({
        url:"../package.json",
        methods:"post",
        data:{          //post请求通过request body 请求参数
            userId:"101"
        },
        //params:{        //get请求通过params来传送参数
        //}
        headers{
            token:"http-test"
        },
    }).then(res=>{
        this.msg = res.data
    })

并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
 
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete 
  }));

全局拦截

    mounted:function(){
        axios.interceptors.request.use(function(config){ //全局拦截request请求
            console.log("request init");
            //这里作请求之前的loading处理
            return config
        })
        axios.interceptors.response.use(function(response){
            console.log("response init")
            //这里作请求完成之后作处理之前的操作
            return response;
        })
    }


.

原文地址:https://www.cnblogs.com/fightjianxian/p/11950294.html