首先安装vue-resource:
npm install vue-resource --save
然后引入
import VueResourse from 'vue-resource'; Vue.use(VueResourse)
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])
Options
Parameter | Type | Description |
---|---|---|
url | string | 请求的UR |
body | Object , FormData , string | request body |
headers | Object | request header |
params | Object | 请求的URL参数对象 |
method | string | 请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 |
timeout | number | 单位为毫秒的请求超时时间 (0 表示无超时时间) |
before | function(request) | 请求发送前的处理函数,类似于jQuery的beforeSend函数 |
progress | function(event) | ProgressEvent回调处理函数 |
credentials | boolean | 表示跨域请求时是否需要使用凭证 |
emulateHTTP | boolean | 发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override |
emulateJSON | boolean | 将request body以application/x-www-form-urlencoded content type发送 |
跨域时使用jsonp
this.$http.jsonp( 'someurl', { params:{ param1:'123456', param2:'7890' } } ).then((response)=>{ console.log(response.data); },error => { console.log(error) });