vue请求封装 使用promise和vue-resource

vue请求封装 使用promise和vue-resource

由于在项目中很多地方都需要用到网络请求,为了使用上的方便,使用ES6的Promise和vue-resource来封装网络请求

// # api.js
import Vue from 'vue';
import router from '../../router';
const API_PATH = '' // # 请求前缀
/**
 * @param  {string} {url 请求地址
 * @param  {string} method 请求方法
 * @param  {Object} params body请求参数
 * @param  {Function} before 发送请求前执行方法
 * @param  {string} prefix 请求地址前缀
 */
function http({
  url,
  method = 'get',
  params = {},
  before = function (request) {
  },
  prefix = API_PATH
}) {
  url = prefix + url;
  return new Promise((resolve, reject) => {
    Vue.http[method](
      url, method == 'get' ? {
        params,
        before,
      } : params, {
        emulateJSON: true
      },
    ).then((res) => {
      resolve(res.data);
    }).catch(res => {
      console.log('warn');
      // 统一处理异常情况
      if (res.status == 500) {
        // 跳转注册页
        router.push('/register');
      }
    });
  })
}
复制代码

params的处理方法get和post有所不同,get中params是作为请求的query,post中的是作为请求的body

基于全局Vue对象使用http

Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
复制代码

before()是发送请求前执行的方法

// # 调用示例 get before
_getPackageList() {
  http({
    url: HTTP_URL.getPackageList,
    params: {
      city_id: this.currentCity.city_id,
      company_id: 0,
      list: 0,
      name: this.$route.query.package_name 
    },
    // # 请求前先中止上一个请求,防止多次请求
    before(request) {
      this.prevRequest && this.prevRequest.abort();
      this.prevRequest = request;
    },
    prefix: appPath
  }).then(res => {
    if (res.code === 200) {
    // # 处理数据 
    }
  });
},
// post
http({
  url: HTTP_URL.saveMemeber,
  params: {..},
  method: "post",
  prefix: appPath
}).then(res => {
  if (res.code === 200) {
  // # 保存成功
  }
});
复制代码

转载于:https://juejin.im/post/5badf8356fb9a05d02610078

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值