Vue生态——vue-resource

本文介绍了一个用于处理Vue中异步请求的插件,包括GET、POST等HTTP方法的使用方式,以及如何配置请求参数、头部信息、超时时间和拦截器等。通过实例演示了不同类型的请求操作。

基本概念

这是一个处理异步请求的插件。

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])
参数
url          string           请求的URL

methods      string           请求的HTTP方法

body                          POST请求时带的参数(request body)

params       Object           GET请求时的URL参数

headers      Object           请求第三方时的请求头部参数(request header)

timeout      number           单位为毫秒的请求超时时间,超过接口就会终止

before    function(request)   请求发送前的处理函数

progress  function(event)     回调处理函数,例如做进度 

credientials  boolean         表示跨域时,是否需要使用凭证

emulateHTTP   boolean         发送PUT、PATCH、DELETE请求时,以POST的方式发送
                              在请求头设置 X-HTTP-Method-Override

emulateJSON   boolean         将request body以 application/x-www-form-urlencoded content type 发送


全局拦截器 interceptors

语法
Vue.http.interceptors.push((request,next) => {
    //...
    //请求发送前的处理逻辑
    //...
    next((response) => {
        //...
        //请求发送后的处理逻辑
        //...
        //根据请求状态,response参数返回给successCallback或errorCallback
        return response
    })
})

DEMO演示


Get请求

get(){
    //使用this.$http发送请求
    this.$http.get("package.json",{

    //传参
    params: {
        userId: "101"
    },
    headers:{
    //往请求头部注入token
    token: "abcd"
    }
})
//请求成功后捕获 res等于success
.then(res =>{
        this.msg = res.data;
    },
    error =>{
        this.msg = error;
    });
}



Post请求

post(){
    this.$http.post("package.json",{
    //直接写要传的参数
    userId: "102"
    },
    {
    //这里写请求配置
    headers:{
        //往请求头部注入access_token
        access_token: "abc"
    }
})
    .then(res =>{
        this.msg = res.data;
        },error => {
            this.mag = error;
    });
}



JSONP请求

jsonp(){
                                                    //这里是参数  这里是默认要设置的
    this.$http.jsonp('https://sug.so.360.cn/suggest',{word:'a'},{jsonp:'callback'})
    .then(res =>{
        this.msg = res.data;
    },error => {
        this.mag = error;
    });
}



全局拦截器的使用

mounted里面定义

mounted: function(){
        Vue.http.interceptors.push(function(request,next){
          console.log("请求发送前");

          //next是请求后,响应完了
          next(function(res){
            console.log("响应了");
            return res;
          });
        });
      },
      //这下面是设置根路径
      http:{
        root:"http://localhost:63342/vue/ImoocMall/"
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值