谈谈Vue.js——vue-resource全攻略

2020-06-16 06:04:52易采站长站整理

then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:


// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(response){
// 响应错误回调
});

// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
// 响应成功回调
}, (response) => {
// 响应错误回调
});

PS:做过.NET开发的人想必对Lambda写法有一种熟悉的感觉。

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

客户端请求方法服务端处理方法
this.$http.get(…)Getxxx
this.$http.post(…)Postxxx
this.$http.put(…)Putxxx
this.$http.delete(…)Deletexxx

options对象

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

参数类型描述
url
string
请求的URL
method
string
请求的HTTP方法,例如:’GET’, ‘POST’或其他HTTP方法
body
Object
,
FormData
string
request body
params
Object
请求的URL参数对象
headers
Object
request header
timeout
number
单位为毫秒的请求超时时间 (
0
表示无超时时间)