Vue.js 使用 Promise 封装 HTTP 请求

2023-05-18 08:33:56

Vue.js 使用 Promise 封装 HTTP 请求

/**
 * Promise 封装 HTTP GET 请求 
 * @param {string} url 请求地址
 * @param {Object} [params] 请求参数
 * @returns {Promise} Promise 对象
 */
function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params })
      .then(resp => {
        if (resp && resp.data) {
          resolve(resp.data);
        } else {
          reject(new Error("请求返回数据为空"));
        }
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * Promise 封装 HTTP POST 请求 
 * @param {string} url 请求地址
 * @param {Object} [data] 请求参数
 * @returns {Promise} Promise 对象
 */
function post(url, data) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(resp => {
        if (resp && resp.data) {
          resolve(resp.data);
        } else {
          reject(new Error("请求返回数据为空"));
        }
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * Vue 插件:$http
 * @param {Vue} Vue Vue 对象
 */
const $http = {
  install: function (Vue) {
    Vue.prototype.$http = {
      get: get,
      post: post
    };
  }
};

export default $http;
  • 作者:
  • 原文链接:
    更新时间:2023-05-18 08:33:56