vue-resource怎么写服务类

vue-resource可以基于全局的Vue对象使用http(vue.http),也可以基于某个Vue实例使用http(this.$http)。
基于全局Vue对象使用http

1
2
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在一个Vue实例内使用$http

1
2
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。

两种场景使用

场景一 基于全局对象使用http(vue.http)

1
Vue.$http.get('/static/address/address.json').then(res => { let list = res.body })

上边是请求本地的json文件,then方法中传入一个参数,响应成功时将返回的数据传到本地的数组中,response.body为返回的请求体。
在实际项目开发过程中,用到的也是全局的,如下所示:

1
let res =await $http.get('/static/address/address.json', {params: param}).then(res => res.json)

会发现没有写vue和this,但是事实是项目中对vue-resource进行了封装,所以直接$http直接可以代替全局的写法

场景二 基于某个vue组件使用http(this.$http)

1
2
3
4
5
6
7
created () {
this.$http.get('http://apis.baidu.com/tiyu', {
params: {num: 10}
}).then((res) => {console.log(res.body)}, (err)=>{
console.log('出错')
})
}

在一个组件中使用vue-resource时,将请求写在钩子函数中,大多数情况写在created钩子函数中。

———————美丽的分割线———————
ps:以上都是开始学习vue的时候做的笔记,最近整理到博客上,也发现了其中的一些不足,慢慢完善