How to encapsulate and use data request axios in vue
This article mainly introduces the relevant knowledge of how to encapsulate and use data request axios in vue, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on how to encapsulate and use data request axios in vue. Let's take a look.
What is axios
To put it simply, Axios is a promise-based HTTP library that can be used in browsers and node.js. We often use the axios request interface to get data in our projects.
Second, download method
Open the terminal directly in the project you are currently using:
Npm install axios-save or yarn add axios III interceptor
Interceptor is the technology that intercepts requests or intercepts responses in the process of data requests.
Request interceptor: to do something when sending a request
Response interceptor: to intercept some operations performed in response, such as login error returning login status
The implementation method is also very simple, directly create a new utils folder under the src file, and create a new js file with any name.
Import axios from "axios" let service=axios.create () service.interceptors.request.use (function (config) {return config;}, function (error) {return Promise.reject (error);}); export default service IV. Encapsulation of the request
Encapsulated requests are usually placed under the api folder, so it is very convenient to use them. As long as you reference them where you use them, you can use them directly.
For example:
Import axios from "axios" let getAction= (url) = > {return new Promise ((resolve,reject) = > {axios ({url,method: "GET"}). Then ((ok) = > {resolve (ok)}). Catch ((err) = > {reject (err)} export default getAction 5. Use
It is also very convenient to use when you have encapsulated the request, refer to it in the .vue file that you use, and use the
/ / import getAction from @ / api/index the article on "how to encapsulate and use data request axios in vue" ends here. Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to encapsulate and use data request axios in vue". If you want to learn more knowledge, you are welcome to follow the industry information channel.