vue--------之axios的使用与二次封装
注意:Vue官方推荐的网络通信库不再是vue-resource了,推荐使用axios。
npm:
$ npm install axios
bower:
$ bower install axios
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
基本使用方法
GET
请求
// Make a request for a user with a given ID
axios.get("/user?ID=12345")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get("/user", {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
POST
请求
axios.post("/user", {
firstName: "Fred",
lastName: "Flintstone"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
同时执行多个请求
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
}));
基本用法很简单。大家一看就知道怎么用。
并发性
下列接口用于处理并发请求(同时处理多个多个request)
- axios.all(iterable)
- axios.spread(callback)
1.正确的使用axios来post数据呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
axios({ method: "post", url: "接口地址", data: { key1: "value1", key2: "value2" }, responseType:"json", transformRequest: [function (data, headers){ //此处是重点,将axios的默认以json方式发送数据 转为 以url string格式发送数据 //URLSearchParams的兼容需要babel-polyfill支持 //如果参数是一维的,可不使用URLSearchParams,自己用key1=value1&key2=value2的格式拼接后返回即可 let q =new URLSearchParams(); for(let iin data){ q.append(i, data[i]); } return q.toString(); }] }); |
2.axios的全局配置以及全局的拦截器
// 超时时间 axios.defaults.timeout = 5000; // request拦截器 var loadinginstace; axios.interceptors.request.use(config => { config.headers["Content-Type"] = "application/x-www-form-urlencoded"; config.transformRequest=[function (data, headers) { let q = new URLSearchParams(); for(let i in data){ q.append(i, data[i]); } return q.toString(); }]; return config }, error => { Message.error({ message: "加载超时" }); return Promise.reject(error) }) // response拦截器 axios.interceptors.response.use(data => {// 响应成功关闭loading return data }, error => { Message.error({ message: "加载失败" }); return Promise.reject(error) })2.axios的二次封装
export const axiosEg = (url,data,method = "post") => { let promise = new Promise(function(resolve, reject) { axios({ method: method, url: url, data:data, }).then(function(res){ resolve(res) }).catch(function(err){ Message.error(err); reject(err) }); }) return promise }4.async/await的使用------------由于项目时间紧直接用的axios,项目结束后用async/await对数据请求进行了封装(es6)可以不在依赖axios。有兴趣的可以自己封装下,这里就不上代码了。有需要可以留言交流------
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: axios在vue中的简单配置与使用
- 下一篇: 关于vue项目中,axios请求方式,跨域请求的处理