Home  >  Article  >  Web Front-end  >  How to encapsulate the get and post methods using axios in vue 2.x

How to encapsulate the get and post methods using axios in vue 2.x

亚连
亚连Original
2018-06-02 17:07:462372browse

This article introduces you to the get and post methods of axios encapsulation in vue 2.x through example code. It is very good and has reference value. Friends who need it can refer to it

vue 2.x axios encapsulation The get and post methods

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);
      })
    })
  }
}

The postfile method

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);
      })
    })
  }

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Sample code to implement image and file upload in vue

NodeJS parent process and child process resource sharing principle and Implementation method

Example of mobile phone number, email regular verification and verification code sent in 60 seconds in vue

The above is the detailed content of How to encapsulate the get and post methods using axios in vue 2.x. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn