详解vue前后台数据交互vue-resource文档

2020-06-13 10:41:31易采站长站整理

// 解析的URL为:/books/1

params

params(可选,对象)

参数对象,可用来提供url中的占位符,多出来的属性拼接url的查询参数。

actions

actions(可选,对象)

可以用来对已有的action进行配置,也可以用来定义新的action。

默认的aciton配置为:


Resource.actions = {
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'delete'},
delete: {method: 'DELETE'}
}

修改默认值action配置


this.$resource(
'/books/{cat}',
{
cat: 1
}, {
charge: {
method: 'POST',
params: {
charge: true
}
}
});

actions对象中的单个action如charge对象可以包含options中的所有属性,且有限即高于iotions对象

options

options(可选,对象)

resource方法执行后返回一个包含了所有action方法名的对象。其包含自定义的action方法

resource请求数据


var resouce = this.$resource('/books/{id}');
// 查询
// 第一个参数为params对象,优先级高于resource发方法的params参数

resoure.get({id: 1}).then(function ( response ) {
this.$set('item', response.item);
});

// 保存

// 第二个参数为要发送的数据
resource.seve({id: 1}, {item: this.item}).then(function () {
// 请求成功回调
}, function () {
// 请求失败回调
});

resource.delete({id: 1}).then(function () {
// 请求成功回调
}, function () {
// 请求失败回调
});

拦截器

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

拦截器的注册


Vue.http.interceptors.push({
request: function ( request ) {
// 更改请求类型为POST
request.method = 'POST';
return request;
},
response: function ( response ) {
// 修改返回数据
response.data = [{
custom: 'custom'
}];
return response;
}
});

工厂函数注册


Vue.http.interceptors.push(function () {
return {
request: function ( request ) {
return request;
},
response: function ( response ) {
return response;
}
}
});
Vue.http.interceptors.push(function ( request, next ) {
// 请求发送前的处理逻辑

next(function () {
// 请求发送后的处理逻辑
// 更具请求的状态, response参数会返回给 successCallback或errorCallback