您的位置:首页 > 产品设计 > UI/UE

浏览器与服务器的交互原理解析(四)-------使用vue-resource进行异步请求

2018-01-10 16:47 826 查看
vue相对于jquery和原生js来说, 通过产生虚拟DOM, 将前端攻城狮从原来繁琐的DOM操作中解放出来, 相应的, ajax基于对DOM节点的操作,进行数据请求的方式在vue中就被弃用了. 转而使用了vue-resource插件, 该插件可以通过XMLHttpRequest或JSONP发起请求并处理响应。也就是说,$.ajax能做的事情,vue-resource插件一样也能做到,而且vue-resource的API更为简洁。另外,vue-resource还提供了非常有用的inteceptor全局拦截功能,使用inteceptor可以在请求前和请求后附加一些行为,比如使用inteceptor在ajax请求时显示loading界面。

一. vue-resource基于底层式get/post请求, 封装了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])
其中: url是请求地址,字符串类型, 可被options对象中url属性覆盖。
        data是要发送的数据, 可以是字符串或者对象类型, 可被options对象中的data属性覆盖。
        options中的参数配置如下:

参数数据类型描述
urlstring请求的URL地址
methodstring默认值为GET,请求的HTTP方法(GET,POST等)
bodyObject, FormDatastring默认值为:' ',需要发送给服务端的数据,

data属性的值对method为POST,PUT,DElETE等请求会作为请求体来传送,对于GET,JSONP等方式的请求将会拼接在URL查询参数中。
paramsObject默认值为:{ } 用来替换url中的模板变量,模板变量中为匹配到的属性添加在URL地址后边作为查询参数。例如:

Vue.http({

    url: 'http://example.com/{book}',

    params: {

        book: 'vue',

        cat: 1

    }

});

最终url为: http//example.com/vue?cat=1
headersObject默认值为:{ },设置HTTP请求头
timeoutnumber默认为:0,单位为 ms。表示请求超时时间。0表示没有超时限制。超时后,将会取消当前请求。
beforefunction(request)默认值为:null,该函数接受请求选项对象作为参数。该函数在发送请求之前执行,vue-resource内部在拦截器最前端调用该方法。
progressfunction(event)ProgressEvent回调处理函数
credentialsboolean表示跨域请求时是否需要使用凭证
emulateHTTPboolean默认值为:false,当值为true是,用HTTP的POST方式PUT,PATCH,DELETE等请求,并设置请求头字段HTTP_Method_Override为原始请求方法。
emulateJSONboolean默认值为:false,当值为true并且data为对象时,设置请求头Content-Type的值为application/x-www-form-urlencoded
   

二. 返回的Response对象

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

data (对象或字符串): 服务端返回的数据,已使用 JSON.parse 解析

ok(布尔值):当HTTP响应状态码在200~299区间时该值为true,表示响应成功

status(数值): HTTP响应状态码

statusText(字符串): HTTP响应状态文本描述

headers(函数): 获取HTTP响应头信息,不传参表示获取整个响应头,返回一个相应头对象。传参表示获取对应的响应头信息

三. vue-resource的使用

1. 在vue单文件中的使用:
<script src="../js/vue.js"></script>
<script src="../js/vue-resource.js"></script>

// 基于全局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);
2. 在vue-cli中使用:
//安装模块包
npm install vue-resource --save

//然后在main.js(入口文件)中引入并注册
import Vue from 'vue';
import VueResource from 'vue-resource'

Vue.use(VueResource);


3. 方法使用实例:

GET方法:
getCustomers: function() {
var vm = this
vm.$http.get(vm.apiUrl)
.then((response) => {
vm.$set('gridData', response.data)
})
},


POST方法:
createCustomer: function() {
var vm = this
vm.$http.post(vm.apiUrl, vm.item)
.then((response) => {
vm.$set('item', {})
vm.getCustomers()
})
this.show = false
}


JSONP方法:
getCustomers: function() {
this.$http.jsonp(this.apiUrl).then(function(response){
this.$set('gridData', response.data)
})
}
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()
})
}

四. RESTful调用: Resource

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

2.  vue-resource提供了另外一种方式访问HTTP——resource服务,resource服务包含以下几种默认的action:

默认的aciton配置为:

Resource.actions = {

    get: {method: 'GET'},

    save: {method: 'POST'},

    query: {method: 'GET'},

    update: {method: 'PUT'},

    remove: {method: 'DELETE'},

    delete: {method: 'DELETE'}

}

3.   resource对象也有两种访问方式:

全局访问:Vue.resource

实例访问:this.$resource

4. 应用实例:
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)
})
}

五. 实现全局拦截

1. 注册拦截器:
Vue.http.interceptors.push((request, next) => {
// ...
// 请求发送前的处理逻辑
// ...
next((response) => {
// ...
// 请求发送后的处理逻辑
// ...
// 根据请求的状态,response参数会返回给successCallback或errorCallback
return response;
})
})


2. 拦截器使用实例: 加载loading插件

Vue.http.interceptors.push((request, next) => {
// 通过控制 组件的`v-show`值显示loading组件
loading.show = true;
next((response) => {
loading.show = false
return response
});
});


关于vue-resource差不多内容都涵盖了, 虽然已经不是官方推荐的插件了, 但是还是有它自身的优点, 关于跨域的处理,另写博客再做详细分析;

好文共享: Vue.js——vue-resource全攻略
                vue前后台数据交互vue-resource文档
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue resource