社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
ps:说明下,从vue2.x开始尤大大推荐使用axios进行数据交互,关于axios后续将继续和大家一起学习。
npm install vue-resource --save
//然后在main.js(入口文件)中引入并注册
import Vue from 'vue';
import VueResource from 'vue-resource'
Vue.use(VueResource)
vue-resource将请求配置分为全局配置、组件实例配置和调用配置这三部分。并且这三部分的优先级依次增高。
使用全局配置设置默认值。
Vue.http.options.root = '/root';
在组件实例化的配置参数http选项中进行配置。
new Vue({
http:{
root: './root',
headers{
Authorization: 'Basic datura'
}
}
})
new Vue({
methods:{
getData(){
this.$http.get({
url: '/api',
headers: {
Authorization: 'Basic datura'
}
}).then(function(res){
//请求成功的回调
},function(err){
//请求失败的回调
})
}
}
})
new Vue({
methods:{
getData(){
//POST请求,带参数
this.$http({
url: '/api',
method: 'POST',
data:{
'username': 'datura_lj',
'password': 123456
},
headers: {
'Content-Type': 'x-wwww-form-urlencoded'
}
}).then(function(res){
//请求成功的回调
},function(err){
//请求失败的回调
})
}
}
})
不同于底层式方法,便捷式方法是其实是对底层方法进行了封装,它提供了7种请求API:
参数说明:
参数 | 数据类型 | 说明 |
---|---|---|
url | string | 请求数据的地址 |
body | Obj, FormData, string | request body |
headers | Obj | request header |
params | Object | 请求的URL参数对象 |
method | string | 请求的HTTP方法,例如:'GET', 'POST'或其他 |
timeout | number | 单位为毫秒请求超时时间 (0 表示无超时时间) |
before | function(request) | 请求发送前的处理函数,类似于jQuery的beforeSend函数 |
progress | function(event) | ProgressEvent回调处理函数 |
credentials | boolean | 表示跨域请求时是否需要使用凭证 |
emulateHTTP | boolean | 发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override |
emulateJSON | boolean | 将request body以application/x-www-form-urlencoded content type发送 |
// 基于全局Vue对象使用http
Vue.http.get('/api', [options]).then(successCallback, errorCallback);
Vue.http.post('/api', [body], [options]).then(successCallback, errorCallback);
// 在一个Vue实例内使用$http
this.$http.get('/api', [options]).then(successCallback, errorCallback);
this.$http.post('/api', [body], [options]).then(successCallback, errorCallback);
methods:{
get1:function(){
//发送get请求
this.$http.get('/api').then(function(res){
//请求成功函数
},function(){
//请求失败函数
});
},
get2:function(){
//发送get请求
this.$http.get('get.do',
{
a:1,
b:2
}
).then(function(res){
//请求成功函数
},function(){
//请求失败函数
});
},
post:function(){
//发送post请求
this.$http.post('post.do',
{
a:1,
b:2
}
).then(function(res){
//请求成功函数
},function(){
//请求失败函数
});
},
put:function(){
this.$http.put('put.do',{
"id": 111,
"hascollect": 1
}).then(function(res){
//请求成功函数
}
},function(err){
//请求失败函数
});
}
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!