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.
Generally speaking, when we use Axios to send a request, the following three steps are involved:
// axios实例的默认配置 const instance = axios.create({ baseURL: '', timeout: 5000, headers: { 'Content-Type': 'application/json' } });
instance.get('/api/getUser', { params: { id: 123 } }).then(res => { console.log(res) }).catch(err => { console.log(err) })
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:
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.
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 } });
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!