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來源:简书著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。
相关文章
相关标签/搜索