方式一步骤:
1、在当前项目中安装vue-resource
- 命令窗口输入:npm install vue-resource --save
2、安装完成后,在main.js中导入
import VueResource from vue-resource //引入
Vue.use(VueResource) //使用
方式二步骤:
1、直接在页面中,通过script标签,引入 vue-resource的脚本文件;
2、引入vue.js和vue-resource.js,注意先后顺序,先引vue.js。记住所有vue插件都需要在vue.js之后加载。
引用:
1、发送get请求:
getInfo() { // get 方式获取数据
this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
console.log(res.body);
})
}
//通过.then拿到服务器返回的数据
2、发送post请求:
postInfo() {
var url = 'http://127.0.0.1:8899/api/post';
// post 方法接收三个参数:
// 参数1: 要请求的URL地址
// 参数2: 要发送的数据对象格式
// 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
console.log(res.body);
});
}
//手动发起的post请求,默认没有表单格式,所以,有的服务器处理不了,通过post方法的第三个参数{ emulateJSON: true }设置提交的内容类型为普通表单数据格式。
3、发送JSONP
请求获取数据:
jsonpInfo() { // JSONP形式从服务器获取数据
var url = 'http://127.0.0.1:8899/api/jsonp';
this.$http.jsonp(url).then(res => {
console.log(res.body);
});
}
4、支持的HTTP方法
vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:
- get(url, [options])
- head(url, [options])
- elete(url, [options])
- jsonp(url, [options])
- post(url, [body], [options])
- put(url, [body], [options])
- patch(url, [body], [options])
注意:
-
url,请求地址。可被options对象中url属性覆盖。
-
body(可选,字符串或对象),要发送的数据,可被options对象中的body属性覆盖。
-
options 请求选项对象
参数 类型 描述 url string 请求的URL method string 请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 body Object,FormDatastring request body params Object 请求的URL参数对象 headers Object request header timeout number 单位为毫秒的请求超时时间 (0 表示无超时时间) before function(request) 请求发送前的处理函数,类似于jQuery的beforeSend函数 progress function(event) ProgressEvent回调处理函数 credentials boolean 表示跨域请求时是否需要使用凭证 emulateHTTP boolean 发送PUT, PATCH, DELETE请求时以HTTP emulateJSON boolean 将request body以application/x-www-form-urlencoded content type发送