VUE--Ajax通信Vue-resource(十六)

一、Vue-resource

vue-resource特点:
 1、体积小:vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
 2、支持主流浏览器:和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持
3、支持Promise API和URI Templates:Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。 URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板
 4、支持拦截器:拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。 拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。

二、安装与导入

安装:
npm install vue-resource
在main.js中导入:
/*引入资源请求插件*/
import VueResource from 'vue-resource'

/*使用VueResource插件*/
Vue.use(VueResource)

src引入,就直接引入文件即可,注意在要vue之后引入

三、基本使用方法

引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http:

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。
  then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:

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

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

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

options | 参数说明:

参数 类型 描述
url string 请求的目标URL
body Object, FormData, string 作为请求体发送的数据
headers Object 作为请求头部发送的头部对象
params Object 作为URL参数的参数对象
method string HTTP方法 (例如GET,POST,...)
timeout number 请求超时(单位:毫秒) (0表示永不超时)
before function(request) 在请求发送之前修改请求的回调函数
progress function(event) 用于处理上传进度的回调函数 ProgressEvent
credentials boolean 是否需要出示用于跨站点请求的凭据
emulateHTTP boolean 是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUT,PATCH和DELETE请求。
emulateJSON boolean 设置请求体的类型为application/x-www-form-urlencoded

通过如下属性和方法处理一个请求获取到的响应对象:

属性 类型 描述
url string 响应的 URL 源
body Object, Blob, string 响应体数据
headers Header 请求头部对象
ok boolean 当 HTTP 响应码为 200 到 299 之间的数值时该值为 true
status number HTTP 响应码
statusText string HTTP 响应状态
方法 类型 描述
text() 约定值 以字符串方式返回响应体
json() 约定值 以格式化后的 json 对象方式返回响应体
blob() 约定值 以二进制 Blob 对象方式返回响应体

四、HTTP请求

  1. GET 请求
    1)请求数获取数据
        methods:{
            get:function(){
                //发送get请求
                this.$http.get('/url地址').then(function(res){
                    document.write(res.body);    
                },function(){
                    console.log('请求失败处理');
                });
            }
        }

如果需要传递数据,可以使用 this.$http.get('/url地址',{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据。

this.$http.get('请求地址',{params : {a:1,b:2}}).then(function(res){
    document.write(res.body);    
},function(res){
    console.log(res.status);
});
  1. 服务器端控制器:
@RestController
public class GoodsController {
    @CrossOrigin
    @GetMapping("/getGoods")
    public Goods getGoods(){
        Goods goods=new Goods();
        goods.setId(1);
        goods.setGoodsName("华为手机");
        goods.setPrice(new BigDecimal("10000.1"));
        goods.setNum(1L);
    return goods;
    }
}

3). 打开即加载



  1. POST请求
    post 发送数据到后端,需要第三个参数 {emulateJSON:true}。
    emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。
methods:{
            post:function(){
                //发送 post 请求
                this.$http.post('/url地址',{name:"学习vue",url:"http://www.baidu.com"},{emulateJSON:true}).then(function(res){
                    document.write(res.body);    
                },function(res){
                    console.log(res.status);
                });
            }
        }
  1. 拦截器
    拦截器可以在请求发送前和发送请求后做一些处理。在response返回给successCallback或errorCallback之前,你可以修改response中的内容,或做一些处理。 例如,响应的状态码如果是404,你可以显示友好的404界面。再比如我们就用拦截器做了登录处理,所以请求发送之前都要通过拦截器验证当前用户是否登陆,否则提示登录页面。


    拦截器
//拦截器
Vue.http.interceptors.push((request, next) => {

  // 修改请求
  request.method = 'POST';

  // continue to next interceptor
  next();
});
请求和响应处理
Vue.http.interceptors.push((request, next)  => {

  // modify request
  request.method = 'POST';

  // continue to next interceptor
  next((response) => {

    // modify response
    response.body = '...';

  });
});

返回一个响应并停止处理

Vue.http.interceptors.push((request, next) => {

  // modify request ...

  // stop and return response
  next(request.respondWith(body, {
    status: 404,
    statusText: 'Not found'
  }));
});
  1. 登录示例

Vue.http.interceptors.push((request, next)  =>{
  //登录成功后将后台返回的TOKEN在本地存下来,每次请求从sessionStorage中拿到存储的TOKEN值
  let TOKEN=sessionStorage.getItem('STORAGE_TOKEN');
  if(TOKEN){
    //如果请求时TOKEN存在,就为每次请求的headers中设置好TOKEN,后台根据headers中的TOKEN判断是否放行
    request.headers.set('TOKEN',TOKEN);
  }
  next((response) => {
    return response;
  });
});


//拦截器
Vue.http.interceptors.push((request, next) => {
//  console.log(Login.item);
var tokens = localStorage.getItem('token');
request.headers.set('Authorization', tokens);
//console.log(request.headers);
help.showLoading = true;
                    
next((response) => {
//console.log(response);
help.showLoading = false;
return response
  })
})

注: sessionStorage.setItem("name", res.data.name); HTML 5 Web 存储在客户端临时存储数据

常见错误:

  1. Avoid using non-primitive value as key, use string/number value instead
    原因为:在v-for中的key必须为字符串或数值类型,不能使用对象。
    解决方法:
 

你可能感兴趣的:(VUE--Ajax通信Vue-resource(十六))