vue中axios怎么封装get和post方法

2023-06-13,,

本篇内容介绍了“vue中axios怎么封装get和post方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

vue 2.x axios 封装的get 和post方法

import axios from 'axios'
import qs from 'qs'
export class HttpService {
  Get(url, data) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: data
      }).then((res) => {
        if (res) {
          //成功回调
          resolve(res);
        }
      }).catch((error) => {
        reject(error);
      })
    })
  }
  Post(url, data) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(data), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        }
      }).then((res) => {
        if (res) {
          //成功回调
          resolve(res);
        }
      }).catch((error) => {
        reject(error);
      })
    })
  }
}

 postfile方法

PostFlie(url, data) {
    return new Promise((resolve, reject) => {
      //根据data对象生成FormData对象
      var temp = new FormData();
      for (var t in data) {
        temp.append(t, data[t]);
      }
      axios.post(url, temp).then((res) => {
        if (res) {
            resolve(res.Data);
        }
      }).catch((error) => {
        reject(error);
      })
    })
  }

“vue中axios怎么封装get和post方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!

《vue中axios怎么封装get和post方法.doc》

下载本文的Word格式文档,以方便收藏与打印。