谈谈Vue.js——vue-resource全攻略
概述
上一篇我们介绍了如何将$.ajax和vue.js结合在一起使用,并实现了一个简单的跨域curd示例。vue.js是数据驱动的,这使得我们并不需要直接操作dom,如果我们不需要使用jquery的dom选择器,就没有必要引入jquery。vue-resource是vue.js的一款插件,它可以通过xmlhttprequest或jsonp发起请求并处理响应。也就是说,$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的api更为简洁。另外,vue-resource还提供了非常有用的inteceptor功能,使用inteceptor可以在请求前和请求后附加一些行为,比如使用inteceptor在ajax请求时显示loading界面。
本文的主要内容如下:
- 介绍vue-resource的特点
- 介绍vue-resource的基本使用方法
- 基于this.$http的增删查改示例
- 基于this.$resource的增删查改示例
- 基于inteceptor实现请求等待时的loading画面
- 基于inteceptor实现请求错误时的提示画面
本文11个示例的源码:
vue-resource特点
vue-resource插件具有以下特点:
1. 体积小
vue-resource非常小巧,在压缩以后只有大约12kb,服务端启用gzip压缩后只有4.5kb大小,这远比jquery的体积要小得多。
2. 支持主流的浏览器
和vue.js一样,vue-resource除了不支持ie 9以下的浏览器,其他主流的浏览器都支持。
3. 支持promise api和uri templates
promise是es6的特性,promise的中文含义为“先知”,promise对象用于异步计算。
uri templates表示uri模板,有些类似于asp.net mvc的路由模板。
4. 支持拦截器
拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。
vue-resource使用
引入vue-resource
<script src="js/vue.js"></script> <script src="js/vue-resource.js"></script>
基本语法
引入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);
在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的es 6的lambda写法:
// 传统写法 this.$http.get('/someurl', [options]).then(function(response){ // 响应成功回调 }, function(response){ // 响应错误回调 }); // lambda写法 this.$http.get('/someurl', [options]).then((response) => { // 响应成功回调 }, (response) => { // 响应错误回调 });
ps:做过.net开发的人想必对lambda写法有一种熟悉的感觉。
支持的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时,客户端的编码风格和服务端的编码风格近乎一致,这可以减少前端和后端开发人员的沟通成本。
客户端请求方法 | 服务端处理方法 |
---|---|
this.$http.get(...) | getxxx |
this.$http.post(...) | postxxx |
this.$http.put(...) | putxxx |
this.$http.delete(...) | deletexxx |
options对象
发送请求时的options选项对象包含以下属性:
参数 | 类型 | 描述 |
---|---|---|
url | string |
请求的url |
method | string |
请求的http方法,例如:'get', 'post'或其他http方法 |
body |
object , formdata string
|
request body |
params | object |
请求的url参数对象 |
headers | object |
request header |
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发送 |
emulatehttp的作用
如果web服务器无法处理put, patch和delete这种rest风格的请求,你可以启用enulatehttp现象。启用该选项后,请求会以普通的post方法发出,并且http头信息的x-http-method-override属性会设置为实际的http方法。
vue.http.options.emulatehttp = true;
emulatejson的作用
如果web服务器无法处理编码为application/json的请求,你可以启用emulatejson选项。启用该选项后,请求会以application/x-www-form-urlencoded作为mime type,就像普通的html表单一样。
vue.http.options.emulatejson = true;
response对象
response对象包含以下属性:
方法 | 类型 | 描述 |
---|---|---|
text() | string |
以string形式返回response body |
json() | object |
以json对象形式返回response body |
blob() | blob |
以二进制形式返回response body |
属性 | 类型 | 描述 |
ok | boolean |
响应的http状态码在200~299之间时,该属性为true |
status | number |
响应的http状态码 |
statustext | string |
响应的状态文本 |
headers | object |
响应头 |
注意:本文的vue-resource版本为v0.9.3,如果你使用的是v0.9.0以前的版本,response对象是没有json(), blob(), text()这些方法的。
curd示例
提示:以下示例仍然沿用上一篇的组件和webapi,组件的代码和页面html代码我就不再贴出来了。
get请求
var demo = new vue({ el: '#app', data: { gridcolumns: ['customerid', 'companyname', 'contactname', 'phone'], griddata: [], apiurl: 'http://211.149.193.19:8080/api/customers' }, ready: function() { this.getcustomers() }, methods: { getcustomers: function() { this.$http.get(this.apiurl) .then((response) => { this.$set('griddata', response.data) }) .catch(function(response) { console.log(response) }) } } })
这段程序的then方法只提供了successcallback,而省略了errorcallback。
catch方法用于捕捉程序的异常,catch方法和errorcallback是不同的,errorcallback只在响应失败时调用,而catch则是在整个请求到响应过程中,只要程序出错了就会被调用。
在then方法的回调函数内,你也可以直接使用this,this仍然是指向vue实例的:
getcustomers: function() { this.$http.get(this.apiurl) .then((response) => { this.$set('griddata', response.data) }) .catch(function(response) { console.log(response) }) }
为了减少作用域链的搜索,建议使用一个局部变量来接收this。
jsonp请求
getcustomers: function() { this.$http.jsonp(this.apiurl).then(function(response){ this.$set('griddata', response.data) }) }
post请求
var demo = new vue({ el: '#app', data: { show: false, gridcolumns: [{ name: 'customerid', iskey: true }, { name: 'companyname' }, { name: 'contactname' }, { name: 'phone' }], griddata: [], apiurl: 'http://211.149.193.19:8080/api/customers', item: {} }, ready: function() { this.getcustomers() }, methods: { closedialog: function() { this.show = false }, getcustomers: function() { var vm = this vm.$http.get(vm.apiurl) .then((response) => { vm.$set('griddata', response.data) }) }, createcustomer: function() { var vm = this vm.$http.post(vm.apiurl, vm.item) .then((response) => { vm.$set('item', {}) vm.getcustomers() }) this.show = false } } })
put请求
updatecustomer: function() { var vm = this vm.$http.put(this.apiurl + '/' + vm.item.customerid, vm.item) .then((response) => { vm.getcustomers() }) }
delete请求
deletecustomer: function(customer){ var vm = this vm.$http.delete(this.apiurl + '/' + customer.customerid) .then((response) => { vm.getcustomers() }) }
使用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'}
resource对象也有两种访问方式:
- 全局访问:vue.resource
- 实例访问:this.$resource
resource可以结合uri template一起使用,以下示例的apiurl都设置为{/id}了:
apiurl: 'http://211.149.193.19:8080/api/customers{/id}'
get请求
使用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) }) }
post请求
使用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 }
put请求
使用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() }) }
{/id}相当于一个占位符,当传入实际的参数时该占位符会被替换。
例如,{ id: vm.item.customerid}中的vm.item.customerid为12,那么发送的请求url为:
http://211.149.193.19:8080/api/customers/12
delete请求
使用remove或delete方法发送delete请求,下面这个请求指定了{/id}。
deletecustomer: function(customer){ var resource = this.$resource(this.apiurl) vm = this resource.remove({ id: customer.customerid}) .then((response) => { vm.getcustomers() }) }
使用inteceptor
拦截器可以在请求发送前和发送请求后做一些处理。
基本用法
vue.http.interceptors.push((request, next) => { // ... // 请求发送前的处理逻辑 // ... next((response) => { // ... // 请求发送后的处理逻辑 // ... // 根据请求的状态,response参数会返回给successcallback或errorcallback return response }) })
在response返回给successcallback或errorcallback之前,你可以修改response中的内容,或做一些处理。
例如,响应的状态码如果是404,你可以显示友好的404界面。
如果不想使用lambda函数写法,可以用平民写法:
vue.http.interceptors.push(function(request, next) { // ... // 请求发送前的处理逻辑 // ... next(function(response) { // ... // 请求发送后的处理逻辑 // ... // 根据请求的状态,response参数会返回给successcallback或errorcallback return response }) })
示例1
之前的curd示例有一处用户体验不太好,用户在使用一些功能的时候如果网络较慢,画面又没有给出反馈,用户是不知道他的操作是成功还是失败的,他也不知道是否该继续等待。
通过inteceptor,我们可以为所有的请求处理加一个loading:请求发送前显示loading,接收响应后隐藏loading。
具体步骤如下:
1.添加一个loading组件
<template id="loading-template"> <div class="loading-overlay"> <div class="sk-three-bounce"> <div class="sk-child sk-bounce1"></div> <div class="sk-child sk-bounce2"></div> <div class="sk-child sk-bounce3"></div> </div> </div> </template>
2.将loading组件作为另外一个vue实例的子组件
var help = new vue({ el: '#help', data: { showloading: false }, components: { 'loading': { template: '#loading-template', } } })
3.将该vue实例挂载到某个html元素
<div id="help"> <loading v-show="showloading"></loading> </div>
4.添加inteceptor
vue.http.interceptors.push((request, next) => { loading.show = true next((response) => { loading.show = false return response }); });
示例2
当用户在画面上停留时间太久时,画面数据可能已经不是最新的了,这时如果用户删除或修改某一条数据,如果这条数据已经被其他用户删除了,服务器会反馈一个404的错误,但由于我们的put和delete请求没有处理errorcallback,所以用户是不知道他的操作是成功还是失败了。
你问我为什么不在每个请求里面处理errorcallback,这是因为我比较懒。这个问题,同样也可以通过inteceptor解决。
1. 继续沿用上面的loading组件,在#help元素下加一个对话框
<div id="help"> <loading v-show="showloading" ></loading> <modal-dialog :show="showdialog"> <header class="dialog-header" slot="header"> <h1 class="dialog-title">server error</h1> </header> <div class="dialog-body" slot="body"> <p class="error">oops,server has got some errors, error code: {{errorcode}}.</p> </div> </modal-dialog> </div>
2.给help实例的data选项添加两个属性
var help = new vue({ el: '#help', data: { showloading: false, showdialog: false, errorcode: '' }, components: { 'loading': { template: '#loading-template', } } })
3.修改inteceptor
vue.http.interceptors.push((request, next) => { help.showloading = true next((response) => { if(!response.ok){ help.errorcode = response.status help.showdialog = true } help.showloading = false return response }); });
总结
vue-resource是一个非常轻量的用于处理http请求的插件,它提供了两种方式来处理http请求:
- 使用vue.http或this.$http
- 使用vue.resource或this.$resource
这两种方式本质上没有什么区别,阅读vue-resource的源码,你可以发现第2种方式是基于第1种方式实现的。
inteceptor可以在请求前和请求后附加一些行为,这意味着除了请求处理的过程,请求的其他环节都可以由我们来控制。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
谈谈因Vue.js引发关于getter和setter的思考
-
谈谈Vue.js——vue-resource全攻略
-
Vue.js使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用
-
谈谈因Vue.js引发关于getter和setter的思考
-
谈谈因Vue.js引发关于getter和setter的思考
-
谈谈Vue.js——vue-resource全攻略
-
vue.js中如何引入vue-resource模块并实现http跨域请求
-
vue.js中如何引入vue-resource模块并实现http跨域请求
-
谈谈因Vue.js引发关于getter和setter的思考
-
Vue.js使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用