Centralized management of axios requests encapsulated in vuejs

15ff9081f789b1dfa0cabf8a2f1def94.jpeg

Centralized management of axios requests encapsulated in vuejs

Preface

Invuejs, using axios to request data usually encapsulates a request method and then calls it in each page, which results in redundant code. This leads to poor code readability and difficulty in maintenance.

In the project, use it aloneaxios or introduce it globally in , and then in each page Calling this is not impossible, but it will make the project's requests very scattered, which is not easy to maintain the code. If some projects with higher requirements need to encapsulate the requests. main.jsaxios

We need to centrally manageaxios requests to facilitate future maintenance.

Unencapsulated code

If it is not encapsulated, you need to introduce it separatelyaxios in a specific single file, and then make a request.

As follows

<template>
    <div>
          <div>
            <el-button type="primary"  @click="handleBtnGetJoke">请求数据</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if="aDatas.length > 0?true:false">清空数据</el-button>
    </div>
</template>

<script setup>
// 引入axios    
import axios from "axios";

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

// 请求数据
async function handleBtnGetJoke() {
    const params = {
        key: 'aa1b7ad08be2a09a4e0d2d46897e2dc8',
        page: page.value,
        pagesize:pagesize.value,
        time: 1418816972
    }
    // 使用axios中的get请求数据
    const response = await axios.get('/api/joke/content/text.php',{params})
    console.log(response);
    if(response.status == 200) {
        const { data } = response.data.result;
        console.log(data);
        aDatas.value = aDatas.value.concat(data);
    }
}

// 加载数据,叠加
function handleBtnLoading() {
    page.value++;
    handleBtnGetJoke(); 
    //getJokeListsData();
}

// 清空数据
function handleBtnClearData() {
    aDatas.value = [];
}
</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 there is no axios encapsulation, then as long as the single-file component in the project needs to request data, it must be introducedaxios, and it needs to be frequently Writeaxios.get()oraxios.post()

If you do not want to import axios repeatedly, you can also import globallymain.js a>axios

import { createApp } from 'vue';

import axios from "axios";

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

const app = createApp(App);
// 全局 挂载axios,在vue2.0里面是挂载在原型下的vue.prototype.$axios = axios,写过vue2.0的代码的应该不会陌生
app.config.globalProperties.$axios = axios

app.use(ElementPlus)

app.mount('#app');

Then in a single file component, you can use it directly

<template>
    <div>
          <div>
            <el-button type="primary"  @click="handleBtnGetJoke">请求数据</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if="aDatas.length > 0?true:false">清空数据</el-button>
    </div>
</template>

<script setup>
// 需要引入getCurrentInstance() 获取当前实例
import { ref,getCurrentInstance  } from "vue";
// 调用getCurrentInstance() 获取axios实例
const { proxy } = getCurrentInstance();

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


async function handleBtnGetJoke() {
    const params = {
        key: 'aa1b7ad08be2a09a4e0d2d46897e2dc8',
        page: page.value,
        pagesize:pagesize.value,
        time: 1418816972
    }
    // 需要proxy.$axios.get() 这样才能使用
    const response = await proxy.$axios.get('/api/joke/content/text.php',{params})
    console.log(response);
    if(response.status == 200) {
        
        const { data } = response.data.result;
        console.log(data);
        aDatas.value = aDatas.value.concat(data);
    }
}

// 加载数据,叠加
function handleBtnLoading() {
    page.value++;
    handleBtnGetJoke(); 
}

// 清空数据
function handleBtnClearData() {
    aDatas.value = [];
}
</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>

For the above code of type, mount axios globally on proxy, and then mount it in the vue file Use proxy.$axios.get() directly, so that you don’t need to introduce axios every time in the single-file component.

But there are also disadvantages. Every time you request data, you need to pass in the params parameter, which is more troublesome. Therefore, we can also encapsulate a getRequest method, encapsulateparams parameters into get request method, so that every time you request data, you don’t need to pass it every time params parameter.

EncapsulationaxiosMethod to request data

1. Encapsulate a request.js file for requesting data. This file encapsulates the axios method of requesting data, as well as request interception and response. Interception.

encapsulates the get and post request methods, as well as request interception and response interception. Generally, it will be placed in the folder under the src directory. api

As shown in the following example

import axios from 'axios';
// 接口地止
const baseUrl = '/api/joke/content/list.php';

// get请求方法封装,具体某个页面当中的get请求方法,可以调用这个方法
export const getJokeLists =  (params)=> {
    return  axios.get(`${baseUrl}`,{
        params:{
            ...params
        }
    })
}

2. Use it in components

In the component, use the method inrequest.js to request data.

As shown in the following example

<template>
    <div>
          <div>
            <el-button type="primary"  @click="getJokeListsData">请求数据</el-button>
            <el-button type="danger" @click="handleBtnClearData" v-if="aDatas.length > 0?true:false">清空数据</el-button>
          <div>
            <ul v-if="aDatas.length > 0?true:false">
                <li class="joke-list" v-for="item in aDatas"
                                    :key="item.hashId">{
    
    { item.content }}
                </li>
                <div class="loading" v-if="aDatas.length > 0?true:false"> 
                    <el-button size="mini"  type="primary" @click="handleBtnLoading" >加载</el-button>
                </div>
            </ul> 
    </div>
</template>

<script setup>
import { getJokeLists } from "../../api/request.js";

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

async function getJokeListsData() {
    // 请求参数
    const params ={
        key: "aa1b7ad08be2a09a4e0d2d46897e2dc8",
        page: page.value,
        pagesize:pagesize.value,
        time: 1418816972
    }
    // 这里的话,直接调用request.js中的方法,进行请求数据,就可以了的
    const response = await getJokeLists(params)
    console.log(response);
    if(response.status == 200) {
        
        const { data } = response.data.result;
        console.log(data);
        aDatas.value = aDatas.value.concat(data);
    }
}


// 加载数据,叠加
function handleBtnLoading() {
    page.value++;
    getJokeListsData();
}

// 清空数据
function handleBtnClearData() {
    aDatas.value = [];
}

</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's axios's get request is encapsulated,

Then, we can directly use get to request. There is no need to write get request code, just call getJust use the request method. Isn’t it very convenient?

Because our get request has been encapsulated in request.js, so we can call it directly. Encapsulation< a i=3>is similarpost

In some well-written projects, axios will be encapsulated, which facilitates code management and reuse, and also facilitates project maintenance

Encapsulation has the benefits of encapsulation, and there are also benefits of not encapsulating. For beginners, it is relatively straightforward to write scattered axios requests, but the encapsulated code requires developers Trace it yourself

The encapsulated code may be difficult for beginners to understand. Therefore, it is recommended for beginners to write scattered code first, wait until they are proficient enough, and then encapsulate it. When they are not very proficient, write scattered code first. In this way, we have a more intuitive understanding of packaging.

Instead of encapsulating the request code as soon as you come up, dig a hole for yourself. Make sure that there are no problems with the scattered code, and then encapsulate it. This way, it is more friendly to beginners.

Cache component status in vuejs-keepAlive

2023-09-30

d50f346963c6992e77553b6b7a921463.jpeg

Before front-end and back-end joint debugging - a front-end’s thoughts before hand-writing code

2023-09-21

c3d2a128f5031691d34a19efe1b14079.jpeg

How to solve cross-domain problems when the local development environment built by vite requests a third-party interface

2023-09-17

fe05befe75c6f7e2be2c204b12c4c281.jpeg

How does a VuePress website use axios to request a third-party interface?

2023-09-16

ae6b56a0cd86e40f25d6fb70d4fbb121.jpeg

Make money by sharing shortened links

2023-09-15

8c93be4930b76b7d727fa93a80545572.jpeg

おすすめ

転載: blog.csdn.net/wzc_coder/article/details/133565034