Home > Web Front-end > JS Tutorial > body text

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

亚连
Release: 2018-06-02 17:07:46
Original
2354 people have browsed it

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);
      })
    })
  }
}
Copy after login

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);
      })
    })
  }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!