Vue进阶(幺伍肆):vue-resource(vue-resource.js)
前言
vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。也就是说,$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的API更为简洁。
vue-resource是一个非常轻量、用于处理HTTP请求的插件,它提供了两种方式来处理HTTP请求:
- 使用Vue.http或this.$http
- 使用Vue.resource或this.$resource
这两种方式本质上没有什么区别,阅读vue-resource的源码可以得知,你可以发现第2种方式其实是基于第1种方式实现的。
此外,vue-resource还提供了拦截器:inteceptor可以在请求前和请求后附加一些行为,这意味着除了请求处理的过程,请求的其他环节都可以由我们来控制。
在Vue.js中,完成ajax请求的方式有两种:vue-resource和 axios。
Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。有关 axios应用详参博文:
《Vue进阶(四):使用 Vuex + axios 发送请求》
vue-resource特点
- 体积小:vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
- 支持主流浏览器:和Vue.js一样,vue-resource除了不支持IE9以下的浏览器,其他主流的浏览器都支持;
- 支持Promise API和URI Templates:Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。 URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板;
- 支持拦截器:拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。 拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共用的处理方式。有关拦截器的具体应用,详参《Vue进阶(幺伍伍):vue-resource 拦截器interceptors使用》。
基本语法
引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http。
基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
以下是一个简单的get使用示例:
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// success callback
}, response => {
// error callback
});
http方法列表
vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:
- get(url, [options])
- head(url, [options])
- delete(url, [options])
- jsonp(url, [options])
- post(url, [body], [options])
- put(url, [body], [options])
- patch(url, [body], [options])
除了jsonp以外,另外6种的API名称都是标准的HTTP方法。当服务端使用REST API时,客户端的编码风格和服务端的编码风格近乎一致,这可以减少前端和后端开发人员的沟通成本。
options对象
发送请求时的options选项对象包含以下属性:
Response
返回对象的参数以及对象的方法如下:
示例代码
简单的post提交
{
// POST /someUrl
this.$http.post('/someUrl', {foo: 'bar'}).then(response => {
// get status
response.status;
// get status text
response.statusText;
// get 'Expires' header
response.headers.get('Expires');
// get body data
this.someData = response.body;
}, response => {
// error callback
});
}
带查询参数和自定义请求头的GET请求
{
// GET /someUrl?foo=bar
this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '...'}}).then(response => {
// success callback
}, response => {
// error callback
});
}
获取图片并使用blob()方法从响应中提取图片的主体内容。
// GET /image.jpg
this.$http.get('/image.jpg', {responseType: 'blob'}).then(response => {
// resolve to Blob
return response.blob();
}).then(blob => {
// use image Blob
});
安装
npm install vue-resource --save
–save参数的作用是在配置文件package.json文件中添加对应的配置。安装成功后, 可以查看package.json文件,会发现多了"vue-resource": "^1.3.4"的配置。具体如下:
"dependencies": {
"vue": "^2.3.3",
"vue-resource": "^1.3.4",
"vue-router": "^2.7.0"
},
应用
通过以上步骤,我们已经安装好了vue-resource,但是在vue-cli中我们如何使用呢?
首先,需要在main.js文件中导入并注册vue-resource:
import VueResource from 'vue-resource'
Vue.use(VueResource)
resource服务应用
vue-resource提供了另外一种方式访问HTTP——resource服务,resource服务包含以下几种默认的action:
- get: {method: 'GET'},
- save: {method: 'POST'},
- query: {method: 'GET'},
- update: {method: 'PUT'},
- remove: {method: 'DELETE'},
- delete: {method: 'DELETE'}
1、resource对象也有两种访问方式:全局访问和局部访问。
//全局访问
Vue.resource
//局部访问
this.$resource
可以结合URI Template一起使用,以下示例的apiUrl都设置为{/id}了:
apiUrl: 'http://22.189.25.95:8080/api/customers{/id}'
{/id}相当于一个占位符,当传入实际的参数时该占位符会被替换。例如,{ id: vm.item.customerId}中的vm.item.customerId为12,那么发送的请求URL为:'
http://22.189.25.95:8080/api/customers/12'
2、使用实例
//使用get方法发送GET请求,下面这个请求没有指定{/id}
getCustomers: function() {
var resource = this.$resource(this.apiUrl),
vm = this;
resource.get().then((response) => {
vm.$set('gridData', response.data);
}).catch(function(response) {
console.log(response);
})
}
//使用save方法发送POST请求,下面这个请求没有指定{/id}
createCustomer: function() {
var resource = this.$resource(this.apiUrl),
vm = this;
resource.save(vm.apiUrl, vm.item).then((response) => {
vm.$set('item', {});
vm.getCustomers();
});
this.show = false;
}
//使用update方法发送PUT请求,下面这个请求指定了{/id}
updateCustomer: function() {
var resource = this.$resource(this.apiUrl),
vm = this;
resource.update({
id: vm.item.customerId
}, vm.item).then((response) => {
vm.getCustomers();
})
}