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 个示例的源码已放到 GitHub,如果您觉得本篇内容不错,请点个赞,或在 GitHub 上加个星星!

GitHub Source

本文的所有示例如下:

各位在阅读这篇文章的内容时,可以先尝试该列表的最后两个示例,这两个示例综合使用了 this.$http 和 inteceptor。

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。

image

View Demo

JSONP 请求

getCustomers: function() {this.$http.jsonp(this.apiUrl).then(function(response){this.$set('gridData', response.data)
	})
}

View Demo

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
		}
	}
})

29

View Demo

PUT 请求

updateCustomer: function() {
	var vm = this
	vm.$http.put(this.apiUrl + '/' + vm.item.customerId, vm.item)
		.then((response) => {vm.getCustomers()
		})
}

30

View Demo

Delete 请求

deleteCustomer: function(customer){
	var vm = this
	vm.$http.delete(this.apiUrl + '/' + customer.customerId)
		.then((response) => {vm.getCustomers()
		})
}

31

View Demo

使用 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) =&gt; {
		vm.$set('gridData', response.data)
	})
	.catch(function(response) {
		console.log(response)
	})

}

View Demo

POST 请求

使用 save 方法发送 POST 请求,下面这个请求没有指定{/id}

createCustomer: function() {var resource = this.$resource(this.apiUrl)
		vm = this
resource.save(vm.apiUrl, vm.item)
	.then((response) =&gt; {
		vm.$set('item', {})
		vm.getCustomers()
	})
this.show = false

}

View Demo

PUT 请求

使用 update 方法发送 PUT 请求,下面这个请求指定了{/id}

updateCustomer: function() {var resource = this.$resource(this.apiUrl)
		vm = this
resource.update({ id: vm.item.customerId}, vm.item)
	.then((response) =&gt; {
		vm.getCustomers()
	})

}

{/id}相当于一个占位符,当传入实际的参数时该占位符会被替换。
例如,{ id: vm.item.customerId}中的 vm.item.customerId 为 12,那么发送的请求 URL 为:

http://211.149.193.19:8080/api/customers/12

View Demo

DELETE 请求

使用 remove 或 delete 方法发送 DELETE 请求,下面这个请求指定了{/id}

deleteCustomer: function(customer){var resource = this.$resource(this.apiUrl)
		vm = this
resource.remove({ id: customer.customerId})
	.then((response) =&gt; {
		vm.getCustomers()
	})

}

View Demo

使用 inteceptor

拦截器可以在请求发送前和发送请求后做一些处理。

image

基本用法

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
	});});

27

View Demo

示例 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
	});});

28

View Demo

总结

vue-resource 是一个非常轻量的用于处理 HTTP 请求的插件,它提供了两种方式来处理 HTTP 请求:

  • 使用 Vue.http 或 this.$http
  • 使用 Vue.resource 或 this.$resource

这两种方式本质上没有什么区别,阅读 vue-resource 的源码,你可以发现第 2 种方式是基于第 1 种方式实现的。

inteceptor 可以在请求前和请求后附加一些行为,这意味着除了请求处理的过程,请求的其他环节都可以由我们来控制。

参考链接:https://github.com/vuejs/vue-resource/tree/master/docs