Vue2.0: How to Use vue3 api to encapsulate Axios

The biggest difference between vue2 and vue3 is that vue2 uses the options API to compare with the composition API of vue3: aggregate code & amp; Logic reuse

How to use vue3 API to encapsulate Axios in vue2.0:
code directly:
1, create API folder in SRC, and create corresponding file

2, encapsulate some methods in Axios, such as get, post…

// http/axios.js
import instance from "./index"
/**
 * @param {String} method  Methods requested: get, post, delete, put
 * @param {String} url The url of the request:
 * @param {Object} data The parameter of the request.
 * @param {Object} config The configuration of the request.
 * @returns {Promise} returns a promise object, which is actually equivalent to the return value of the axios request data
 */

const axios = ({
    method,
    url,
    data,
    config
}) => {
    method = method.toLowerCase();
    if (method == 'post') {
        return instance.post(url, data, {...config})
    } else if (method == 'get') {
        return instance.get(url, {
            params: data,
            ...config
        })
    } else if (method == 'delete') {
        return instance.delete(url, {
            params: data,
            ...config
        }, )
    } else if (method == 'put') {
        return instance.put(url, data,{...config})
    } else {
        console.error('未知的method' + method)
        return false
    }
}
export default axios

3. Encapsulate some Axios request interception and response interception in the index
here, I basically don’t do any interception, I can add them if I need

// http/index.js
import axios from 'axios'

//Create an instance of axios 
var instance = axios.create({
  baseURL: "http://192.168.0.7:8366", //interface unified domain name
  timeout: 6000, //set timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;',
  }
})
let loading;
//Number of requests being made
let requestCount = 0
//Show loading
const showLoading = () => {
  if (requestCount === 0 && !loading) {
  
  }
  requestCount++;
}
//hidden loading
const hideLoading = () => {
  requestCount--
  if (requestCount == 0) {
  
  }
}

//Request Interceptors 
instance.interceptors.request.use((config) => {
  showLoading()
  // Determine if a token exists before each request is sent, and if it does, add the token to the header of each http request, so you don't have to add it manually for each request
  const token = window.localStorage.getItem('token');
  token && (config.headers.Authorization = token)
  //If the request method is post, the data parameter is converted to a JSON string
  if (config.method === 'POST') {
    config.data = JSON.stringify(config.data);
  }
  return config;
}, (error) =>
  // What to do with request errors
  Promise.reject(error)).

//response interceptor
instance.interceptors.response.use(( response) => {
  hideLoading()
  //response success
  console.log('Interceptor reported an error').
  return response.data;
}, (error) => {
  console.log(error)
  //Response error
  if (error.response && error.response.status) {
    const status = error.response.status
    switch (status) {
      case 400:
        message = 'Request Error';
        break;
      case 401:
        message = 'Request Error';
        break;
      case 404:
        message = 'Error requesting address';
        break;
      case 408:
        message = 'Request timed out';
        break;
      case 500:
        message = 'Internal server error!' ;
        break;
      case 501:
        message = 'Service not implemented!' ;
        break;
      case 502:
        message = 'Gateway error!' ;
        break;
      case 503:
        message = 'Service unavailable!' ;
        break;
      case 504:
        message = 'Gateway timeout!' ;
        break;
      case 505:
        message = 'HTTP version is not supported';
        break;
      default:
        message = 'Request failed'
    }
    ElMessage.error(message);
    return Promise.reject(error);
  }
  return Promise.reject(error);
});


export default instance;

4. Finally, import these files into the NAV file

import axios from "../api/axios"
//Example request
//get
//If you need to wear parameters, you can still use the template string splice `/api/v1/0?id=${id}` and write the id in parentheses
export const mokePostD = (id) => {
    return axios({
        url: '/api/v1/0',
        method: "post",
       	data,
        config: {
            headers: {
                // 'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}
//post
export const mokePost = () => {
    return axios({
        url: '/api/v1/0',
        method: "post",
		data,
        config: {
            headers: {
                // 'Request-Type': 'wechat'
            },
            timeout: 10000
        }
    })
}

5. Page


import { mokePost, mokePostD } from "../../api/nav";
import { ref, onMounted } from "@vue/composition-api";

export default{
	setup(props, { root }){

onMounted(() => {
      mokePost().then((res) => {
        console.log(res);
      
      });

}
	}


}


Read More: