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中的参数配置如下:
参数 | 数据类型 | 描述 |
---|---|---|
url | string | 请求的URL地址 |
method | string | 默认值为GET,请求的HTTP方法(GET,POST等) |
body | Object, FormDatastring | 默认值为:' ',需要发送给服务端的数据, data属性的值对method为POST,PUT,DElETE等请求会作为请求体来传送,对于GET,JSONP等方式的请求将会拼接在URL查询参数中。 |
params | Object | 默认值为:{ } 用来替换url中的模板变量,模板变量中为匹配到的属性添加在URL地址后边作为查询参数。例如: Vue.http({ url: 'http://example.com/{book}', params: { book: 'vue', cat: 1 } }); 最终url为: http//example.com/vue?cat=1 |
headers | Object | 默认值为:{ },设置HTTP请求头 |
timeout | number | 默认为:0,单位为 ms。表示请求超时时间。0表示没有超时限制。超时后,将会取消当前请求。 |
before | function(request) | 默认值为:null,该函数接受请求选项对象作为参数。该函数在发送请求之前执行,vue-resource内部在拦截器最前端调用该方法。 |
progress | function(event) | ProgressEvent回调处理函数 |
credentials | boolean | 表示跨域请求时是否需要使用凭证 |
emulateHTTP | boolean | 默认值为:false,当值为true是,用HTTP的POST方式PUT,PATCH,DELETE等请求,并设置请求头字段HTTP_Method_Override为原始请求方法。 |
emulateJSON | boolean | 默认值为: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动词来表示增,删,改,查实现对服务端数据操作的一种架构模式
默认的aciton配置为:
Resource.actions = {
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
}
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
全局访问: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全攻略