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

1,176 阅读1分钟

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) {
  // # 保存成功
  }
});