axios get及post方法代碼示例&&方法封裝

axios get及post方法代碼示例

get方法:php

show: function(){
       //get方式

 //賦值給變量self
 var self = this;

 var url = "hotcity.json";
  axios.get(url,{
      params:{
      username: "金星老師"
   }
  })
.then(function (response) {
    self.stu = response.data.data.hotCity;
    console.log(response.data.data.hotCity);
})
.catch(function (error) {
   console.log(error);
})

}

post方法:html

show: function(){
       //post方式
 //var url = "http://bugwhy.com/php/index/getNews.php";
 var url = "http://localhost:8000/login";
       axios.post(url,{
           name: this.username,
  password: this.password
 },{
           "headers": {"Content-Type": "application/x-www-form-urlencodeed"}
 }).then(function(res){
       console.log(res.data);
  })
  .catch(function (error) {
      console.log(error);
                 })

}

 axios方法封裝

通常狀況下,咱們會用到的方法有:GET,POST,PUT,PATCH,封裝方法以下:ios

 

 

封裝後的方法的使用

一、在main.js文件裏引用以前寫好的文件,個人命名爲http.jsjson

 

 二、在須要的地方之間調用,如圖所示:axios

 

 

說明:app

GET調用方法以下,其中url是接口地址post

this.$get(url).then((res) {

//代碼

});

 POST調用方法以下,其中url是接口地址,data是請求的數據。this

this.$post(url,data).then({

//代碼

});

 PATCH調用方法以下,其中url是接口地址,data是請求的數據url

this.$patch(url,data).then({

//代碼

});

 PUT調用方法以下,其中url是接口地址,data是請求的數據spa

this.$put(url,data).then({

//代碼

});

 

做者:陳楠酒肆連接:http://www.jianshu.com/p/3b5e453f54f5來源:簡書著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索