SoFunction
Updated on 2025-04-03

Detailed explanation of how to encapsulate axios requests in vue and centrally manage them

Preface

existvuejsIn, useaxiosWhen requesting data, a request method is generally encapsulated and then called in each page, which causes code redundancy, resulting in poor code readability and difficulty in maintaining.

Used separately in the projectaxiosOr inGlobal introductionaxios, and then call it in each page. This is not impossible, but it will make the project requests very scattered, which is not easy to maintain. If some projects with relatively high requirements, the requests need to be encapsulated.

We need toaxiosRequest centralized management to facilitate future maintenance.

Unencapsulated code

If it is not encapsulated, it needs to be introduced separately in a specific single file.axios, and then make the request.

As shown below

<template>
    <div>
          <div>
            <el-button type="primary"  @click="handleBtnGetJoke">Request data</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if=" > 0?true:false">Clear data</el-button>
    </div>
</template>

<script setup>
// Introduce axiosimport axios from "axios";

let aDatas = ref([]);
let page = ref(1);
let pagesize = ref(5);

// Request dataasync function handleBtnGetJoke() {
    const params = {
        key: 'aa1b7ad08be2a09a4e0d2d46897e2dc8',
        page: ,
        pagesize:,
        time: 1418816972
    }
    // Use get request data in axios    const response = await await ('/api/joke/content/',{params})
    (response);
    if( == 200) {
        const { data } = ;
        (data);
         = (data);
    }
}

// Load data, overlayfunction handleBtnLoading() {
    ++;
    handleBtnGetJoke(); 
    //getJokeListsData();
}

// Clear datafunction handleBtnClearData() {
     = [];
}
</script>

<style scoped>
.joke-list {
    list-style-type: decimal;
    list-style-position: outside;
    padding: 5px 0;
    border-bottom: dashed 1px #ccc;
}

.loading {
    margin: 0 auto;
    text-align:center;
}
</style>

If notaxiosEncapsulation, as long as the single file component in the project needs to request data, it must be introducedaxios, and it requires frequent writing()or()

If you don't want to introduce it againaxios, can also beIn the file, performaxiosThe global introduction of

import { createApp } from 'vue';

import axios from "axios";

import ElementPlus from 'element-plus';
//import 'element-plus/lib/theme-chalk/';   
import 'element-plus/dist/';
import App from './';

const app = createApp(App);
// Global mount axios, which is mounted under the prototype in vue2.0. $axios = axios, those who have written vue2.0 should be familiar with it.$axios = axios

(ElementPlus)

('#app');

In a single file component, it can be used directly

<template>
    <div>
          <div>
            <el-button type="primary"  @click="handleBtnGetJoke">Request data</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if=" > 0?true:false">Clear data</el-button>
    </div>
</template>

<script setup>
// GetCurrentInstance() needs to be introduced to get the current instanceimport { ref,getCurrentInstance  } from "vue";
// Call getCurrentInstance() to get the axios instanceconst { proxy } = getCurrentInstance();

let aDatas = ref([]);
let page = ref(1);
let pagesize = ref(5);


async function handleBtnGetJoke() {
    const params = {
        key: 'aa1b7ad08be2a09a4e0d2d46897e2dc8',
        page: ,
        pagesize:,
        time: 1418816972
    }
    // proxy.$() is required to use    const response = await proxy.$('/api/joke/content/',{params})
    (response);
    if( == 200) {
        
        const { data } = ;
        (data);
         = (data);
    }
}

// Load data, overlayfunction handleBtnLoading() {
    ++;
    handleBtnGetJoke(); 
}

// Clear datafunction handleBtnClearData() {
     = [];
}
</script>

<style scoped>
.joke-list {
    list-style-type: decimal;
    list-style-position: outside;
    padding: 5px 0;
    border-bottom: dashed 1px #ccc;
}

.loading {
    margin: 0 auto;
    text-align:center;
}
</style>

The code above the type,axiosGlobally mounted onproxyThen you canvueUse directly in the fileproxy.$()So, in this way, there is no need to introduce it in a single file component every timeaxiosNow.

But there are also disadvantages, so every time you request data, you need toparamsPassing parameters in, this is more troublesome, so we can also encapsulate onegetRequest method,paramsParameter encapsulation togetIn the request method, every time you request data, you don't need to pass it every time.paramsParameters are here.

Methods to encapsulate axios request data

1. Encapsulate oneFile, used to request data, in this file, encapsulatesaxiosMethods for requesting data, as well as request interception and response interception.

EncapsulatedgetandpostRequest method, as well as request interception and response interception. Usually placedsrcIn the directoryapiin folder.

As shown in the following example

import axios from 'axios';
// Interface stopconst baseUrl = '/api/joke/content/';

// The get request method encapsulates, the get request method in a specific page can be called this methodexport const getJokeLists =  (params)=> {
    return  (`${baseUrl}`,{
        params:{
            ...params
        }
    })
}


2. Use in components

In the component, useThe method in the request data.

As shown in the following example

<template>
    <div>
          <div>
            <el-button type="primary"  @click="getJokeListsData">Request data</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if=" > 0?true:false">Clear data</el-button>
          <div>
            <ul v-if=" > 0?true:false">
                <li class="joke-list" v-for="item in aDatas"
                                    :key="">{{  }}
                </li>
                <div class="loading" v-if=" > 0?true:false"> 
                    <el-button size="mini"  type="primary" @click="handleBtnLoading" >load</el-button>
                </div>
            </ul> 
    </div>
</template>
<script setup>
import { getJokeLists } from "../../api/";
let aDatas = ref([]);
let page = ref(1);
let pagesize = ref(5);
async function getJokeListsData() {
    // Request parameters    const params ={
        key: "aa1b7ad08be2a09a4e0d2d46897e2dc8",
        page: ,
        pagesize:,
        time: 1418816972
    }
    // If you are here, just call the method in the process and request data.    const response = await getJokeLists(params)
    (response);
    if( == 200) {
        const { data } = ;
        (data);
         = (data);
    }
}
// Load data, overlayfunction handleBtnLoading() {
    ++;
    getJokeListsData();
}
// Clear datafunction handleBtnClearData() {
     = [];
}
</script>
<style scoped>
.joke-list {
    list-style-type: decimal;
    list-style-position: outside;
    padding: 5px 0;
    border-bottom: dashed 1px #ccc;
}
.loading {
    margin: 0 auto;
    text-align:center;
}
</style>

You will find that if the page is encapsulatedaxiosofgetask,

Then, we can use it directlygetRequested, no need to writegetThe requested code is called directlygetThe request method is enough, isn't it very convenient?

Because oursgetRequest, inIt has been encapsulated, so we can just call it directly.postSimilar

Anything that is written in a relatively standard way will be correctaxiosEncapsulated, which facilitates code management and reuse and also facilitates project maintenance

Packaging has the benefits of packaging, not packaging, and also the benefits of not packaging. For beginners, write scatteredaxiosThe request is more direct, and the encapsulated code needs to be traced by the developer himself

Encapsulated code may be difficult for beginners to understand, so for beginners, it is recommended to write scattered code first, wait until you are proficient enough, and then encapsulate it. When you are not very proficient, write scattered code first. In this way, you have a more intuitive understanding of encapsulation.

Don't encapsulate the request code as soon as you start, dig a hole for yourself, make sure that there is no problem with the scattered code, and then encapsulate it. This will be more friendly to beginners.

This is the article about how to encapsulate axios requests and centrally manage them in vue. This is the end. For more related contents of Vue encapsulation axios requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!