1、安装
npm install vue-resource
2、使用
import VueResource from 'vue-resource';
Vue.use(VueResource);
this.$http.get("http://localhost/test.php").then(
function (res) {
// 处理成功的结果 alert(res.body);
},function (res) {
// 处理失败的结果
}
);
传递数据到后端
this.$http.post("http://localhost/test.php",{name:"zhangsan"},{emulateJSON:true}).then(
function (res) {
// 处理成功的结果
alert(res.body);
},function (res) {
// 处理失败的结果
}
);
有如下方法:
- get(url, [options])
- head(url, [options])
- delete(url, [options])
- jsonp(url, [options])
- post(url, [body], [options])
- put(url, [body], [options])
- patch(url, [body], [options])
options
Parameter | Type | Description |
url | string | URL to which the request is sent |
body | Object, FormData,string | Data to be sent as the request body |
headers | Object | Headers object to be sent as HTTP request headers |
params | Object | Parameters object to be sent as URL parameters |
method | string | HTTP method (e.g. GET, POST, ...) |
timeout | number | Request timeout in milliseconds (0 means no timeout) |
before | function(request) | Callback function to modify the request options before it is sent |
progress | function(event) | Callback function to handle the of uploads |
credentials | boolean | Indicates whether or not cross-site Access-Control requests should be made using credentials |
emulateHTTP | boolean | Send PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header |
emulateJSON | boolean | Send request body as application/x-www-form-urlencoded content type
|
response
Property | Type | Description |
url | string | Response URL origin |
body | Object, Blob, string | Response body data |
headers | Header | Response Headers object |
ok | boolean | HTTP status code between 200 and 299 |
status | number | HTTP status code of the response |
statusText | string | HTTP status text of the response |
Method | Type | Description |
text() | Promise | Resolves the body as string |
json() | Promise | Resolves the body as parsed JSON object |
blob() | Promise | Resolves the body as Blob object
|
resource可以在全局用:Vue.resource,也可以在组件中使用:this.$resource;方法的调用格式:
- resource(url, [params], [actions], [options])
默认调用方法如下所示:
get: {method:'GET'},
save: {method:'POST'},
query: {method:'GET'},
update: {method:'PUT'},
remove: {method:'DELETE'},
delete: {method:'DELETE'}
eg:
var resource =this.$resource('someItem{/id}');
1. resource.get({id:1}).then(response=> {
this.item=response.body;
});
2. resource.save({id:1}, {item:this.item}).then(response=> {
// success callback
}, response=> {
// error callback
});
3.
resource.delete({id:1}).then(response=> {
// success callback
}, response=> {
// error callback
});
还有其他。。,例子可以结合服务网关zuul来实现数据列表实现
mounted : function() {
this.$http.post(contextPath + "/service/getList.json",[]).then(function(response) { console.log(response); if (response.ok) { var body = response.body; if (body.status === 200) { this.tableData = body.data; } } }, function() { console.log(response); }); }