首页 > 技术文章 > axios 正确打开方式

lhl66 2017-10-06 00:04 原文

一、安装
1、 利用npm安装npm install axios --save
2、 利用bower安装bower install axios --save
3、 直接利用cdn引入<script src="https://unpkg.com/axios/dist/axios.min.js"></script>(vue框架的直接忽略)
bind(this)很多人喜欢在外面定义一个that,里面用that来指向外部的this是一个道理。为了解决无法访问到 Vue 实例
.Catch错误处理

axios 并不能 use,只能每个需要发送请求的组件中即时引入
为了解决这个问题,有两种开发思路,一是在引入 axios 之后,修改原型链,二是结合 Vuex,封装一个 aciton。
import axios from 'axios'
这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题
Vue.prototype.$ajax = axios

vue-resource不改变this指向;axios会改变 存下 var _this=this;/var that = this;

发送一个GET请求
//通过给定的ID来发送请求
axios.get('/user?ID=12345')
.then(function(response){
  console.log(response);
})
.catch(function(err){
  console.log(err);
});
//以上请求也可以通过这种方式来发送
axios.get('/user',{
  params:{
    ID:12345
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(err){
  console.log(err);
});


发送一个POST请求

axios.post('/user',{
  firstName:'Fred',
  lastName:'Flintstone'
})
.then(function(res){
  console.log(res);
})
.catch(function(err){
  console.log(err);
});


3、一次性并发多个请求
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){
//当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
}))

推荐阅读