Vue.js——vue-resource详细介绍
概述
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
地址:https://github.com/keepfool/vue-tutorials/tree/master/03.Ajax/vue-resource
本文的所有示例如下:
- http get示例
- http jsonp示例
- http post示例
- http put示例
- http delete示例
- resource get示例
- resource save示例(HTTP POST)
- resource update示例(HTTP PUT)
- resource remove示例(HTTP DELETE)
- inteceptor示例1——ajax请求的loading界面
- inteceptor实例2——请求失败时的提示对话框
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可以在请求前和请求后附加一些行为,这意味着除了请求处理的过程,请求的其他环节都可以由我们来控制。
参考链接:https://github.com/vuejs/vue-resource/tree/master/docs
Vue.js——vue-resource详细介绍的更多相关文章
- vue对比其他框架详细介绍
vue对比其他框架详细介绍 对比其他框架 — Vue.jshttps://cn.vuejs.org/v2/guide/comparison.html React React 和 Vue 有许多相似之处 ...
- (vue.js)Vue element tab 每个tab用一个路由来管理?
(vue.js)Vue element tab 每个tab用一个路由来管理? 来源:网络整理 时间:2017/5/13 0:24:01 关键词: 关于网友提出的“ (vue.js) ...
- vue中eslintrc.js配置最详细介绍
本文是对vue项目中自带文件eslintrc.js的内容解析, 介绍了各个eslint配置项的作用,以及为什么这样设置. 比较详细,看完能对eslint有较为全面的了解,基本解除对该文件的疑惑. /* ...
- Vue.js 学习入门:介绍及安装
Vue.js 是什么? Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架.与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用.Vue 的核心库只关注视图层 ...
- vue学习之用 Vue.js + Vue Router 创建单页应用的几个步骤
通过vue学习一:新建或打开vue项目,创建好项目后,接下来的操作为: src目录重新规划——>新建几个页面——>配置这几个页面的路由——>给根实例注入路由配置 src目录重整 在项 ...
- (vue.js)vue中引用了别的组件 ,如何使this指向Vue对象
Vue中引用了别的组件 ,如何使this指向Vue对象 今天学习Vue组件传值, 通过创建Vue实例, 广播和监听实现传值, 但是传值之后无法直接将得到的值应用到Vue对象, 因为这相当于引用改了别的 ...
- js模块化开发——require.js的用法详细介绍(含jsonp)
RequireJS的目标是鼓励代码的模块化,它使用了不同于传统<script>标签脚本加载步骤.可以用它回事.优化代码,但其主要的目的还是为了代码的模块化.它鼓励在使用脚本以moudle ...
- Awesome Vue.js vue.js学习资源链接大全 中文
https://blog.csdn.net/caijunfen/article/details/78216868
- Vue.js系列(一):Vue项目创建详解
引言 Vue.js作为目前最热门最具前景的前端框架之一,其提供了一种帮助我们快速构建并开发前端项目的新的思维模式.本文旨在帮助大家认识Vue.js,并详细介绍使用vue-cli脚手架工具快速的构建Vu ...
- 1. vue.js介绍
1. 什么是vue.js Vue.js 是目前最火的一个前端框架,React是最流行的一个前端框架(React除了开发网站,还可以开发手机App, Vue语法也是可以用于进行手机App开发的,需要借助 ...
随机推荐
- 云数据库RDS MySQL 版
阿里云关系型数据库(Relational Database Service,简称RDS)是一种稳定可靠.可弹性伸缩的在线数据库服务.基于阿里云分布式文件系统和SSD盘高性能存储,RDS支持MySQL. ...
- Postgresql 监控sql之 pg_stat_statements模块
postgresql.confpg_stat_statements.max = 1000000pg_stat_statements.track = allpg_stat_statements.trac ...
- .Net Core Grpc 实现通信
.Net Core 3.0已经把Grpc作为一个默认的模板引入,所以我认为每一个.Net程序员都有学习Grpc的必要,当然这不是必须的. 我在我的前一篇文章中介绍并创建了一个.Net Core 3.0 ...
- python3.7 安装Scrapy 失败问题
python的Scrapy框架,需要Twisted依赖以及VC++ 14 以上的环境,这些就不再赘述.讲讲今天安装Twisted和Scrapy遇到的其他问题. 首先就是直接安装Twisted成功后,安 ...
- multivariate_normal 多元正态分布
多元正态分布 正态分布大家都非常熟悉了,多元正态分布就是多维数据的正态分布,其概率密度函数为 上式为 x 服从 k 元正态分布,x 为 k 维向量:|Σ| 代表协方差矩阵的行列式 二维正态分布概率密度 ...
- 可能是把 Java 内存区域讲的最清楚的一篇文章
出处: 可能是把 Java 内存区域讲的最清楚的一篇文章 Java 内存区域详解 写在前面 (常见面试题) 基本问题 拓展问题 一 概述 二 运行时数据区域 2.1 程序计数器 2.2 Java 虚 ...
- response.getWriter().wirte和out.print()的区别
1.首先介绍write()和print()方法的区别: (1).write():仅支持输出字符类型数据,字符.字符数组.字符串等 (2).print():可以将各种类型(包括Object)的数据通 ...
- sql server delete语句
delete语句 --DELETE 语句用于删除表中的行 语法:delete from 表名称 where 列名称 = 值 --可以在不删除表的情况下删除所有的行.这意味着表的结构.属性和索引都是完整 ...
- Hadoop网页监控配置
接之前的内容http://www.cnblogs.com/jourluohua/p/8734406.html 在之前那的内容中,仅实现了Hadoop的安装和运行,距离实际使用还有很远.现在先完成一个小 ...
- @Validated @RequestBody @RequestParam配合使用校验参数
1. @Validated @RequestBody 配合使用 两者搭配进行参数的校验,要想自己捕获该异常,需要自定义全局异常处理器 2. @Validated @RequestParam 配合使 ...