Encapsulating Axios in Vue projects


There must be some operations when we write Vue projects. We will process the data, so we need to encapsulate a function to send requests; Before the request or response, we need to deal with the following:

//Export a function that can send requests
import axios from 'axios'
*Import according to your own project. If you need to jump back, import router
*If you need to store this, import the locally stored JS you have written

//Create an Axios instance
const instance = axios.create({
//Request interceptor
       //What to do before the request, such as adding the request header config.header. Custom = 'xxx' // the return value must be return config after the request is completed
//Response interceptor
//Response, res is the data of the response
//We can capture data and process it
  //Look at the data structure and click on it, so that the data can be used directly
  return res.XXX
  //Exception caught
  //Bring the original data intact
  return res
  //Response failed
  //Response failed做一些处理 // 处理完也要返回一个promise return Promise.reject(err)

*Because our original intention is to export a function that can send requests. The previous processing is to take the data * * and use it directly
export default (url,method,data) =>{
  //We have encapsulated an Axios, so we use this to send requests
   //An expression can be written in the array, and the result must be a string. The request processing method is unified in lowercase regardless of case
   [method.toLowerCase() === 'get'? 'params' : 'data']:data


In main.js:

import http from '@/axios.js'

//Add to the prototype of Vue so that you can get this

Vue.prototype.$http = http


Recommended Today

IOS segmented pop-up window

Recently, I encountered a demand similar to the segmented pop-up window of Gaode map (as shown in the figure below). I didn’t find relevant information on the Internet, so I wrote one myself, hoping to provide you with ideas. Realization effect The idea is that when the pop-up window is in the first segment, add […]