axios get及post方法代码示例&&方法封装
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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号