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" //注意:第二個參數(shù)用于傳遞參數(shù)
},{
headers:{ //第三個參數(shù)才是option選項
token:"tom"
}
}).then(res=>{
this.msg = res.data
})
- 全局配置
axios({
url:"../package.json",
methods:"post",
data:{ //post請求通過request body 請求參數(shù)
userId:"101"
},
//params:{ //get請求通過params來傳送參數(shù)
//}
headers{
token:"http-test"
},
}).then(res=>{
this.msg = res.data
})
并發(fā)請求
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
}));
全局?jǐn)r截
mounted:function(){
axios.interceptors.request.use(function(config){ //全局?jǐn)r截request請求
console.log("request init");
//這里作請求之前的loading處理
return config
})
axios.interceptors.response.use(function(response){
console.log("response init")
//這里作請求完成之后作處理之前的操作
return response;
})
}
更具體的文檔解析請戳https://www.npmjs.com/package/axios#axiosoptionsurl-config-1