Preface
existvuejs
In, useaxios
When 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 projectaxios
Or inGlobal introduction
axios
, 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 toaxios
Request 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 notaxios
Encapsulation, 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, perform
axios
The 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,axios
Globally mounted onproxy
Then you canvue
Use directly in the fileproxy.$()
So, in this way, there is no need to introduce it in a single file component every timeaxios
Now.
But there are also disadvantages, so every time you request data, you need toparams
Passing parameters in, this is more troublesome, so we can also encapsulate oneget
Request method,params
Parameter encapsulation toget
In the request method, every time you request data, you don't need to pass it every time.params
Parameters are here.
Methods to encapsulate axios request data
1. Encapsulate oneFile, used to request data, in this file, encapsulates
axios
Methods for requesting data, as well as request interception and response interception.
Encapsulatedget
andpost
Request method, as well as request interception and response interception. Usually placedsrc
In the directoryapi
in 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 encapsulatedaxios
ofget
ask,
Then, we can use it directlyget
Requested, no need to writeget
The requested code is called directlyget
The request method is enough, isn't it very convenient?
Because oursget
Request, inIt has been encapsulated, so we can just call it directly.
post
Similar
Anything that is written in a relatively standard way will be correctaxios
Encapsulated, 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 scatteredaxios
The 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!