vue-resource 是一个用来发送 XMLHttpRequest 请求的 Vue 插件,它的功能和 jQuery 中的 $.ajax 差不多。有了 vue-resource,简单的 AJAX 请求就不需要手动封装了。
安装
这里使用 npm 安装,在项目目录中输入:
npm install vue-resource --save-dev如果 npm 速度慢的话,也可以使用 cnpm。
使用
首先需要在 main.js 中引入 vue-resource:
import VueResource from 'vue-resource' // 引入 vue-resource
Vue.use(VueResource) // 挂载插件引入并挂载后全局都能使用。
下面使用 get 方式请求 data.json 文件:
this.$http.get('data.json').then(data => {
console.log(data) // 在控制台输出结果
this.contents = data.body // 把请求到的数据传给 contents
}, error => {
console.log(error) // 如果出错就在控制台输出错误信息
}).get 方法有两个参数,第一个参数是 url,第二个参数是配置选项。
如果需要获取响应内容可以调用 then 方法,then 方法可以接收两个回调函数。
第一个回调函数会在请求成功后触发,可以用来接收数据。
第二个回调函数会在请求出错时触发,可以用来接收错误信息。
要发送的数据可以写在 url 后面。
无论请求成功还是失败都会返回一个对象,下面是返回值说明:
| 返回值 | 类型 | 说明 |
|---|---|---|
url | string | 请求的 url |
body | Object or Blob or string | 后端返回的内容 |
headers | Header | 响应标头 |
ok | boolean | 状态码在 200 – 299 为 true |
status | number | HTTP 状态码 |
statusText | string | HTTP 状态文本 |
请求成功和请求失败都会返回同样的对象。
下面使用 post 方式给 https://www.xxxx.com/test.php 发送请求:
this.$http.post('https://www.xxxx.com/test.php', 'data=hello', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
}
}).then(data => {
console.log(data.body) // 在控制台输出后端返回的内容
}, error => {
console.log(error) // 如果出错就在控制台输出错误信息
}).post 的第一个参数是 url,第二个参数是要发送的数据,第三个参数是配置选项。
.post 要获取响应内容还是调用 then 方法,参数和返回内容和上面的 .get 是一样的。
除了 .get 和 .post 外,vue-resource 还提供了以下几种快捷方法:
delete(url, config)jsonp(url, config)head(url, config)put(url, body, config)patch(url, body, config)
参数中的 url 就是要请求的 url,body 就是要发送的内容,config 就是配置选项。
配置选项需要传入一个对象,下面是配置选项说明:
| 参数 | 类型 | 说明 |
|---|---|---|
url | string | 要请求的 url |
body | Object or FormData or string | 要发送的数据 |
headers | Object | HTTP 请求头 |
params | Object | Parameters object to be sent as URL parameters |
method | string | 请求方式(get 或 post) |
responseType | string | 接收响应的类型(json 或 blob 或 text) |
timeout | number | 请求超时,单位为毫秒 |
credentials | boolean | 是否应使用凭据发出跨站点访问控制请求 |
emulateHTTP | boolean | 设置 X-HTTP-Method-Override 请求头 |
emulateJSON | boolean | 对发送的数据进行 url 编码 |
before | function(request) | 在发送请求之前执行的回调函数 |
uploadProgress | function(event) | 上传进度改变时执行的回调函数 |
downloadProgress | function(event) | 下载进度改变时执行的回调函数 |
注意!请求头,也就是 headers 参数是需要手动设置的,否则在发送 POST 请求的时候可能会报错。
除了在 $http 中调用外也可以直接在 Vue 全局对象中调用 http。
下面直接调用 Vue.http 发送 post 请求:
let submit = 'data=123' // 要发送的数据
Vue.http({
url: 'https://www.xxxx.com/text.php',
body: submit,
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'post',
timeout: 20000
}).then(data => {
this.contents = data.body // 把接收到的数据传给 content
}, error => {
alert('出错了!错误代码:' + error.status) // 显示错误码
})注意!上传文件和普通 post 请求的 HTTP 请求头是不一样的。