axios get及post方法代碼示例
get方法:
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方法:
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,封裝方法如下:


封裝后的方法的使用
1、在main.js文件里引用之前寫好的文件,我的命名為http.js

2、在需要的地方之間調用,如圖所示:

說明:
GET調用方法如下,其中url是接口地址
this.$get(url).then((res) {
//代碼
});
POST調用方法如下,其中url是接口地址,data是請求的數據。
this.$post(url,data).then({
//代碼
});
PATCH調用方法如下,其中url是接口地址,data是請求的數據
this.$patch(url,data).then({
//代碼
});
PUT調用方法如下,其中url是接口地址,data是請求的數據
this.$put(url,data).then({
//代碼
});
作者:陳楠酒肆
鏈接:http://www.jianshu.com/p/3b5e453f54f5
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
