Several ways to encapsulate axios in Vue

Several ways to encapsulate axios in Vue

Basic Edition

Step 1: Configure Axios

First, create a Service.js, which stores the axios configuration and interceptors, and finally exports an axios object. I usually use elementUI more often, you can also use your own UI library here.

import axios from 'axios'
import { Message, Loading } from 'element-ui'
const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment let loadingInstance = null //Here is loading
//Use the create method to create an axios instance export const Service = axios.create({
  timeout: 7000, // Request timeout baseURL: ConfigBaseURL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// Add request interceptor Service.interceptors.request.use(config => {
  loadingInstance = Loading.service({
    lock: true,
    text: 'loading...'
  })
  return config
})
// Add response interceptor Service.interceptors.response.use(response => {
  loadingInstance.close()
  // console.log(response)
  return response.data
}, error => {
  console.log('TCL: error', error)
  const msg = error.Message !== undefined ? error.Message : ''
  Message({
    message: 'Network error' + msg,
    type: 'error',
    duration: 3 * 1000
  })
  loadingInstance.close()
  return Promise.reject(error)
})

The specific interceptor logic depends on the specific business. I don't have any logic here, I just added a global loading.

Step 2: Encapsulate the request

Here I create another request.js, which contains the specific request.

import {Service} from './Service'
export function getConfigsByProductId(productId) {
  return Service({
    url: '/manager/getConfigsByProductId',
    params: { productId: productId }
  })
}
export function getAllAndroidPlugins() {
  return Service({
    url: '/manager/getAndroidPlugin ',
    method: 'get'
  })
}
export function addNewAndroidPlugin(data) {
  return Service({
    url: '/manager/addAndroidPlguin',
    data: JSON.stringify(data)
  })
}

Of course, you can also encapsulate the URL again and put it in another file. I think this is meaningless and will increase the complexity. The main thing to pay attention to here is the naming problem. It is recommended to name it according to the function. For example, here I use request method + function or content + parameters. In this way, the name getConfigsByProductId is also very clear.

Step 3: Use

In the vue component

import {getAllAndroidPlugins,getConfigsByProductId,addNewAndroidPlugin} from '@/api/request.js'

getAllAndroidPlugins()
.then(res=>{

})

Global use in main.js

import {Service} from '@/api/Service.js'
Vue.prototype.$axios=Service

Advanced version

With the upgrade of vue cli, core-js\babel and other dependencies have also been upgraded. Now you can use async/await as you like. Therefore, this encapsulation is to upgrade the previous Promise to async await. First, it is still the same. Encapsulate axios first

//Service.js
import axios from 'axios'
const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment //Use the create method to create an axios instance export const Service = axios.create({
  timeout: 7000, // Request timeout baseURL: ConfigBaseURL,
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// Add request interceptor Service.interceptors.request.use(config => {
  return config
})
// Add response interceptor Service.interceptors.response.use(response => {
  // console.log(response)
  return response.data
}, error => {
  return Promise.reject(error)
})

At this point you have obtained an axios object, and then I recommend a commonly used library, mainly used to handle async errors: await-to-js. The code is continued from above.

import to from 'await-to-js'
export function isObj(obj) {
  const typeCheck = typeof obj!=='undefined' && typeof obj === 'object' && obj !== null 
  return typeCheck && Object.keys(obj).length > 0
}
export async function _get(url, qs,headers) {
  const params = {
    url,
    method: 'get',
    params: qs ? qs : ''
  }
  if (headers) { params.headers = headers }
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

When encapsulating get, you only need to consider parameter, use await-to-js to capture errors during await, return data only when successful, and use the interceptor when an error occurs.

export async function _get(url, qs,headers) {
  const params = {
    url,
    method: 'get',
    params: isObj(qs) ? qs : {}
  }
  if (isObj(headers)) {params.headers = headers}
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

This is the post I packaged

export async function _post(url, qs, body) {
  const params = {
    url,
    method: 'post',
    params: isObj(qs) ? qs : {},
    data: isObj(body) ? body : {}
  }
  const [err, res] = await to(Service(params))
  if (!err && res) {
    return res
  } else {
    return console.log(err)
  }
}

It can be directly introduced when used, or it can be encapsulated multiple times

//a.vue
<script>
import{_get}from './Service'
export default{
	methods:{
    	async test(){
        const res = await _get('http://baidu.com')
       }
    }
}
</script>

The above is the details of several methods of Vue encapsulating Axios. For more information about Vue encapsulating Axios, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed example of using typescript to encapsulate axios in Vue3
  • How to encapsulate axios in Vue
  • How to simply encapsulate axios in vue
  • How to encapsulate axios request with vue
  • Detailed explanation of AXIOS encapsulation in Vue

<<:  Docker Swarm from deployment to basic operations

>>:  Centos7.5 installs mysql5.7.24 binary package deployment

Recommend

MySQL paging analysis principle and efficiency improvement

MySQL paging analysis principle and efficiency im...

Use js to call js functions in iframe pages

Recently, I have been working on thesis proposals ...

Display and hide HTML elements through display or visibility

Sometimes we need to control whether HTML elements...

Two ways to build a private GitLab using Docker

The first method: docker installation 1. Pull the...

Detailed usage of kubernetes object Volume

Overview Volume is the abstraction and virtualiza...

Steps to install MySQL 5.7 in binary mode and optimize the system under Linux

This article mainly introduces the installation/st...

Explanation of several ways to run Tomcat under Linux

Starting and shutting down Tomcat under Linux In ...

How to use Docker to build a development environment (Windows and Mac)

Table of contents 1. Benefits of using Docker 2. ...

How to modify the default network segment of Docker0 bridge in Docker

1. Background When the Docker service is started,...

You may need a large-screen digital scrolling effect like this

The large-screen digital scrolling effect comes f...