axios的使用


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

 

    });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM