Vue’s component-based development method makes our front-end development more flexible and efficient, and in this process, data interaction with the back-end is inevitable. Axios is a good data request framework. It provides a convenient API interface, is simple to use, reliable, and easy to expand, so we chose to integrate it into the Vue project. In this article, we will introduce how to encapsulate Axios into a practical request method for easy use in Vue components.
Introduction to Axios
Generally speaking, when we use Axios to send a request, the following three steps are involved:
- Create an Axios instance:
// axios实例的默认配置 const instance = axios.create({ baseURL: '', timeout: 5000, headers: { 'Content-Type': 'application/json' } });
- Send a request:
instance.get('/api/getUser', { params: { id: 123 } }).then(res => { console.log(res) }).catch(err => { console.log(err) })
- Respond to the request result:
instance.interceptors.response.use(res => { if (res.status === 200) { return res.data; } else { throw new Error(res.status); } }, err => { throw new Error(err); })
The use of Axios is very simple and clear, but if every time When used in Vue components, these codes must be written repeatedly, which is time-consuming and error-prone. Therefore, we can encapsulate it into a general request method:
Axios request encapsulation
We can use Promise, an asynchronous programming method, to encapsulate the Axios request into a general method and then unify it Process the returned results.
import axios from 'axios'; axios.defaults.baseURL = ''; axios.defaults.headers.post['Content-Type'] = 'application/json'; axios.defaults.timeout = 5000; // 请求拦截器 axios.interceptors.request.use( config => { // 将token添加到请求头中 if (localStorage.getItem('accessToken')) { config.headers.Authorization = localStorage.getItem('accessToken'); } return config; }, error => { return Promise.reject(error); } ); // 响应拦截器 axios.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { if (error.response.status) { switch (error.response.status) { case 401: // token过期,跳转到登录页 break; case 404: // 请求资源不存在 break; default: // 其他错误提示 break; } return Promise.reject(error.response); } } ) export default function request(options) { return new Promise((resolve, reject) => { axios(options).then(res => { resolve(res.data); }).catch(error => { reject(error); }) }) }
In the above code, we create an Axios instance and set its default configuration, and also add request and response interceptors. In the encapsulated request method, we use Promise to return the result of the request.
- In the request interceptor, we can add Token to the request header, or we can also customize the request here.
- In the response interceptor, we can perform special processing on the response results, such as jumps to status code errors, resource non-existence prompts, or other error prompts, etc.
Request method usage
After encapsulating the Axios request into a general method, we can use it in the Vue component. When calling, we only need to pass the basic parameters of the request:
import request from '@/utils/request'; export function fetchData() { return request({ url: '/api/list', method: 'get' }) }
Similarly, requests for HTTP methods such as GET, POST, PUT, DELETE, and PATCH are supported. Just specify different methods in the parameters.
request({ url: '/api/user', method: 'post', data: { username: 'admin', password: '123456' } }); request({ url: '/api/user', method: 'put', params: { id: 123 }, data: { username: 'admin', password: '123456' } }); request({ url: '/api/user', method: 'delete', params: { id: 123 } });
Conclusion
This article explains in detail how to encapsulate the Axios request method through the integration and encapsulation of Axios in the Vue project. This encapsulation method can greatly reduce the amount of repeated code writing, improve development efficiency, and also facilitate the unified processing of request results. During use, we can adjust and expand its configuration and interceptors as needed to meet different needs.
The above is the detailed content of vue integrates axios encapsulation request. For more information, please follow other related articles on the PHP Chinese website!

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

Key goals and advantages of HTML5 include: 1) Enhanced web semantic structure, 2) Improved multimedia support, and 3) Promoting cross-platform compatibility. These goals lead to better accessibility, richer user experience and more efficient development processes.

The goal of HTML5 is to simplify the development process, improve user experience, and ensure the dynamic and accessible network. 1) Simplify the development of multimedia content by natively supporting audio and video elements; 2) Introduce semantic elements such as, etc. to improve content structure and SEO friendliness; 3) Enhance offline functions through application cache; 4) Use elements to improve page interactivity; 5) Optimize mobile compatibility and support responsive design; 6) Improve form functions and simplify verification process; 7) Provide performance optimization tools such as async and defer attributes.

HTML5transformswebdevelopmentbyintroducingsemanticelements,multimediacapabilities,powerfulAPIs,andperformanceoptimizationtools.1)Semanticelementslike,,,andenhanceSEOandaccessibility.2)Multimediaelementsandallowdirectembeddingwithoutplugins,improvingu

TherealdifferencebetweenusinganIDversusaclassinCSSisthatIDsareuniqueandhavehigherspecificity,whileclassesarereusableandbetterforstylingmultipleelements.UseIDsforJavaScripthooksoruniqueelements,anduseclassesforstylingpurposes,especiallywhenapplyingsty


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
