axios不光在vue上用,在angular和react上也能用。在vue-resource停止维护后,axios是一个很好的替代品。
npm install axios -g 安装axios
import Axios from 'axios'; 在main.js中引入axios
Vue.prototype.$axios = Axios; 将其挂到vue原形链上。
Axios.defaults.baseURL='http://****'; 设置基本请求网址
created(){ function test(a,b){ console.log(a); console.log(b); } //console.log('lal',this.$axios);
//get请求
this.$axios.get("lunbo.php",{params:{id:'120'}}).then(res=>{console.log(res)}).catch(err=>{console.log(err)}); //post请求
this.$axios.post("msg.php",'content={"name":"lisi","age":"19"}') .then(res=>{console.log(res)}) .catch(err=>{console.log(err)}); //合并请求
this.$axios.all([ this.$axios.get('lunbo.php',{params:{id:20}}), this.$axios.post('msg.php','content={"name":"si","age":"18"}') ]).then(this.$axios.spread(test)).catch(err=>{console.log(err)}) }
//合并请求,注意接收的函数参数就按顺序接的,test函数的第一个参数是接的get返回的,第二个是post的。
拦截器
axios的拦截器就是在请求发送前做些处理,然后发送处理过后的请求。
Axios.interceptors.request.use(function(config){
//做一些处理
return config; //然后返回
});
//得到响应后,在做一些处理,然后返回处理后的结果。
Axios.interceptors.response.use(function(config){
//做一些处理
return config; //然后返回
});