遇见Vue.js

  • 关键词:Vue.js – 读书笔记

十二、服务端通信

Vue.js可以构建一个完全依赖后端服务的应用,同时也可以与服务端进行数据交互来同步界面的动态更新。Vue.js本身并没有提供与服务端通信的接口,但是通过插件的形式实现了基于AJAX、JSONP等技术的服务端通信。

vue-resourse是一个通过XMLHttpRequest或JSONP技术实现异步加载服务端数据的插件。

image

vue-resourse提供了数据获取各个阶段的钩子,使得我们可以对数据获取过程进行更好的控制。

参数配置

image

    //全局配置
    Vue.http.options.root = '/root'
    //组件实例配置
    new Vue({
        http: {
            root: '/root',
            headers: {
                Authorization: 'Basic Yxsdlfjui'
            }
        }
    })
    //方法调用时配置
    new Vue({
        ready: function(){
            this.$http.get({
                url: '',
                headers: {
                    Authorization: 'Basic Yxsdlfjui'
                }
            }).then(function(response){
                //成功
            }, function(response){
                //失败
            })
        }
    })

headers配置

image

基本HTTP调用

(1)底层方法

Vue.http(option)全局调用

this.$http(option)组件实例调用

以上两种调用方式接受相同的option参数,都返回Promise对象。不同的是,全局调用方法回调中的this指向window,而组件实例调用方式回调指向组件实例。

(2)便捷方法

以下是vue-resource提供的便捷方法列表:

image

    //POST请求
    this.$http.post(
        'http://example.com/book/create',
        //请求体中药发送给服务器端的数据
        {
            cat: '1',
            name: 'newbook'
        },
        {
            'headers': {
                'Content-Type': 'x-www-form-urlencoded'
            }
        }
    ).then(function(response){
        //成功回调
    }, function(response){
        //失败回调
    })

请求选项对象

在调用HTTP请求方法时,可以传入选项对象来控制请求。


类型 说明
url(字符串) 请求的URL地址
method(字符串) 默认值为GET,请求的HTTP方法(GET,POST等)
data(对象或字符串) 作为请求体或者拼接在url查询参数中
params(对象) 用来替换url中的模板变量,模板变量中未匹配到的属性添加在URL地址后边作为查询参数
headers(对象) 设置HTTP的请求头
xhr(对象) 默认值为null,该对象中的属性都会应用到原生xhr实例对象上,源码:if(_isPlainObject(request.xhr)){_.extend(xhr,request.xhr);}
upload(对象) 默认值为null,该对象的属性都会应用到原生xhr实例对象的upload属性上,源码同上
jsonp(字符串) 默认值为callback,JSONP请求中回调函数的名字。image
timeout(数值) 默认值为0ms,表示请求超时时间
beforeSend(函数) 默认值为null,该函数接受请求选项对象作为参数
emulateHTTP(布尔值) 默认值为false,用HTTP的POST方法发送PUT,PATCH,DELETE等请求,并设置请求头字段HTTP-Method-Override为原始请求方法
emulateJSON(布尔值) 默认值为false,当值为true并且data为对象时,设置请求头Content-Type的值为application/x-www-form-urlencoded
crossOrigin(布尔值) 默认值为null,表示是否跨域

response对象

response对象包含服务端返回的数据,以及HTTP响应状态、响应头等信息。


类型 说明
data(对象或字符串) 服务端返回的数据
ok(布尔值) HTTP响应状态码在200-299之间
statue(数值) HTTP响应状态码
statusText(字符串) HTTP响应状态文本描述
headers(函数) 获取HTTP响应头信息,不传参表示获取整个响应头,返回一个响应头对象;传参表示获取对应的响应头信息
request(对象)  

RESTful调用

RESTful调用方式就是客户端通过HTTP动词来表示增、删、改、查实现对服务端数据操作的一种架构模式。

拦截器

可以全局进行拦截器设置,拦截器可以在请求发送前或响应返回时做一些特殊的处理。

image

跨域AJAX

很早的时候,由于浏览器安全策略,AJAX确实只能在同域的情况下发送。但是目前很多浏览器已经开始支持XMLHttpRequest2(其引入了大量的新特性,其替代品XDomainRequest)。


类型 说明
XMLHttpRequest2 CORS 判断当前浏览器是否支持,以及服务端启用CORS
XDomainRequest 如果vue-resourse不支持XMLHttpRequest2,则会降级使用此种方法

Promise

vue-resourse基本HTTP调用和RESTful调用action方法执行后都会返回一个Promise对象,该Promise对象提供了then,catch,finallay等常用方法来注册回调函数。

image

方法 说明
Promise.all() The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
Promise.prototype.catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected) (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)).
Promise.prototype.finally() The finally() method returns a Promise. When the promise is settled, whether fulfilled or rejected, the specified callback function is executed. This provides a way for code that must be executed once the Promise has been dealt with to be run whether the promise was fulfilled successfully or rejected.
Promise.prototype.then() The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
Promise.race() The Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
Promise.reject() The Promise.reject(reason) method returns a Promise object that is rejected with the given reason.
Promise.resolve() The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a “then” method), the returned promise will “follow” that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

url模板

vue-resourse使用url-template库来解析url模板。

    var template = require('url-template');
    var email = template.parse('/{email}/{folder}/{id}');
    //返回 '/user@domain/test/42'
    emailUrl.expand({
        email: 'user@domain',
        folder: 'test',
        id: 42
    });

vue-async-data

vue-async-data是一个异步加载数据状态指示的插件,它本身并不支持异步获取服务端数据的功能,仅仅指示数据目前是处于加载状态还是已经加载完毕。通过不同的状态我们可以设置加载动画效果等。

    var Vue = require('vue')
    var VueAsyncData = require('vue-async-data');
    Vue.use(VueAsyncData)
    Vue.component('example', {
       data: {},
       asynData: function(resolve, reject){
           //数据加载成功时调用resolve(data),此时$loadingAsyncData会被设置为false(vm.$set('$loadingAsyncData', false))
           //数据加载成功时调用reject(data)
       }
    });
    //==========================
    <div v-if="$loadingAsyncData">Loading...</div>

    //有时候,我们需要手动去服务端获取最新数据来更新界面,这时需要调用组件的实例方法来重新加载数据
    vm.reloadAsyncData()

$.http.post方法变为OPTIONS方法

在跨域情况下,对于非简单请求(PUT,DELETE,Content-Type为application/json),浏览器会在真实请求前额外发起一次类型为OPTIONS的请求。只有服务器正确响应了OPTIONS请求后,浏览器才会发起真实的请求。

服务端需要开启CORS支持,同时需要设置响应头如下:

Access-Control-Allow-Methods: POST,GET,PUT,DELETE,OPTIONS