zoukankan      html  css  js  c++  java
  • 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,或者在请求失败时,提供共通的处理方式。

    二、安装与引用

      NPM: npm install vue-resource --save-dev

    /*引入Vue框架*/
    import Vue from 'vue'
    /*引入资源请求插件*/
    import VueResource from 'vue-resource'
    
    /*使用VueResource插件*/
    Vue.use(VueResource)

      src引入,就直接引入文件即可,注意在要vue之后引入

    三、语法

      引入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) => {
        // 响应错误回调
    });

      1、支持的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时,客户端的编码风格和服务端的编码风格近乎一致,这可以减少前端和后端开发人员的沟通成本。

      2、options对象

      发送请求时的options选项对象包含以下属性:

      3、emulateHTTP的作用

      如果Web服务器无法处理PUT, PATCH和DELETE这种REST风格的请求,你可以启用enulateHTTP现象。启用该选项后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实际的HTTP方法。

    Vue.http.options.emulateHTTP = true;

      4、emulateJSON的作用

      如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。启用该选项后,请求会以application/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。

    Vue.http.options.emulateJSON = true;

    四、使用实例

    var demo = new Vue({
        el: '#app',
        data: {
            gridColumns: ['customerId', 'companyName', 'contactName', 'phone'],
            gridData: [],
            apiUrl: 'http://192.168.118.221:8080/api/customers'
        },
        mounted: function() {
            this.getCustomers()
        },
        methods: {
            getCustomers: function() {
                this.$http.get(this.apiUrl).then((response) => {
                    this.$set('gridData', response.data)
                },(response) => {
                    console.log("出错了");
                }).catch(function(response) {
                    console.log(response)
                })
            }
        }
    });
      这段程序的then方法里提供了successCallbackerrorCallback。catch方法用于捕捉程序的异常,catch方法和errorCallback是不同的,errorCallback只在响应失败时调用,而catch则是在整个请求到响应过程中,只要程序出错了就会被调用。
      在then方法的回调函数内,你也可以直接使用this,this仍然是指向Vue实例的。为了减少作用域链的搜索,建议使用一个局部变量来接收this。

    五、使用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://211.149.193.19:8080/api/customers{/id}'

      {/id}相当于一个占位符,当传入实际的参数时该占位符会被替换。例如,{ id: vm.item.customerId}中的vm.item.customerId为12,那么发送的请求URL为:http://211.149.193.19: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();
        })
    }

    六、使用inteceptor

      拦截器可以在请求发送前和发送请求后做一些处理。在response返回给successCallback或errorCallback之前,你可以修改response中的内容,或做一些处理。 例如,响应的状态码如果是404,你可以显示友好的404界面。再比如我们就用拦截器做了登录处理,所以请求发送之前都要通过拦截器验证当前用户是否登陆,否则提示登录页面。

    Vue.http.interceptors.push(function(request, next) {
        // ...
        // 请求发送前的处理逻辑
        // ...
        next(function(response) {
            // ...
            // 请求发送后的处理逻辑
            // ...
            // 根据请求的状态,response参数会返回给successCallback或errorCallback
            return response
        })
    })

      1、拦截器实例:

      (1)为请求添加loading效果

      通过inteceptor,我们可以为所有的请求处理加一个loading:请求发送前显示loading,接收响应后隐藏loading。

      具体步骤如下:

    //1、添加一个loading组件
    <template id='loading-template'>
        <div class='loading-overlay'></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;
        });
    });

      我们继续,当用户在画面上停留时间太久时,画面数据可能已经不是最新的了,这时如果用户删除或修改某一条数据,如果这条数据已经被其他用户删除了,服务器会反馈一个404的错误,但由于我们的put和delete请求没有处理errorCallback,所以用户是不知道他的操作是成功还是失败了。你问我为什么不在每个请求里面处理errorCallback,这是因为我比较懒。这个问题,同样也可以通过inteceptor解决。

      (2)为请求添加共同的错误处理方法

    //1、继续沿用上面的loading组件,在#help元素下加一个对话框
    <div id='help'>
        <loading v-show='showLoading' ></loading>
        <modal-dialog :show='showDialog'>
            <header class='dialog-header' slot='header'>
                <h3 class='dialog-title'>Server Error</h3>
            </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请求:

      (1)使用Vue.http或this.$http

      (2)使用Vue.resourcethis.$resource

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

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

     

  • 相关阅读:
    学习笔记(5)——实验室集群LVS监控Web界面配置
    学习笔记(4)——实验室集群管理结点IP配置
    Java中List集合去除重复数据的方法
    Android App内部自动更新Library的使用(转载)
    AppBarLayout+TabLayout+RecyclerView+ViewPager+Fragment(布局悬浮)
    126、android html唤醒APP(转载)
    第三方免费加固横向对比(转载)
    124、@JavascriptInterface
    123、 android Retrofit 介绍和使用(转载)
    win10专业版激活步骤
  • 原文地址:https://www.cnblogs.com/goloving/p/8665421.html
Copyright © 2011-2022 走看看