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; //然后返回
});