We talked about the basic usage of axios before [axios] basic use of axios , in the actual Vue project, we do not use this method. At that time, the standardization of the project was not realized. There was no strict division of components and modules, but everything was written in an html file. Now we need to see how to use axios from the perspective of front-end engineering.
Zero. Preparation
Suppose we have a Vue project. The App root component contains a Left component and a Right component. There is a button in the Left component. Click and send a GET request. There is a button in the Right component. Click it to send a POST request. The basic page composition is as follows:
First, you need to install the axios package before you can use axios in your project. Execute npm i axios -S on the terminal to install axios into the project.
1, When a request needs to be sent Import axios into vue component and use
script label content of Left component:
<script> // Import axios module import axios from 'axios' export default { data() { return { bookList: {} } }, methods: { // Click event // < button @ Click = "getinfo" > send GET request < / button > async getInfo() { const { data: res } = await axios.get('http://www.liulongbin.top:3006/api/getbooks') console.log(res) // Generally, the requested data is transferred to data this.bookList = res } } } </script>
script label content of Right component:
<script> // Import axios module import axios from 'axios' export default { methods: { // Click event // < button @ Click = "postinfo" > send POST request < / button > async postInfo() { const { data: res } = await axios.post('http://www.liulongbin.top:3006/api/post', { name: 'zs', age: 20 }) console.log(res) // The process of transferring data to data will not be demonstrated again } } } </script>
Can successfully request, but the disadvantage of this method is that every time you use axios, you have to import it once, as long as this vue components are used for axios, so it is necessary to import the axios module. The components cannot be used with each other (not common), which is troublesome. So we want axios to be globally available.
2, Mount axios on the Vue prototype and configure the request root path
(1) Because we want axios to be available globally, we need to use it in main JS file. The steps are as follows:
- Import axios module
- Mount axios on the Vue prototype.
import Vue from 'vue' import App from './App.vue' // 1. Import axios module import axios from 'axios' Vue.config.productionTip = false // 2. Mount axios on the Vue prototype Vue.prototype.$http = axios new Vue({ render: h => h(App) }).$mount('#app')
[note] when mounting axios on Vue prototype, the name of $HTTP is arbitrary, which means that we have mounted an attribute (method) named $HTTP on Vue prototype, and its value is axios. Traditionally, we all name this attribute $http.
(2) To simplify For the call of vue component instance, you can configure a request root path. When you use it later, you only need to pass in the part after the root path.
import Vue from 'vue' import App from './App.vue' // 1. Import axios module import axios from 'axios' Vue.config.productionTip = false // 3. Configure request root path axios.defaults.baseURL = 'http://www.liulongbin.top:3006' // 2. Mount axios on the Vue prototype Vue.prototype.$http = axios new Vue({ render: h => h(App) }).$mount('#app')
(3) Usage in components:
- You no longer need to import the axios module. Delete the import code directly
- every last. Vue components can be regarded as a Vue instance, because a property named $http is mounted on the Vue prototype, and Vue component is another Vue instance, so you can use this$ http get axios, and then you can use it normally.
- Since the request root path is configured, the first parameter of the GET/POST request can be directly passed into the part after the root path.
script label content of Left component:
<script> // You no longer need to import the axios module. Delete the import code directly export default { data() { return { bookList: {} } }, methods: { async getInfo() { const { data: res } = await this.$http.get('/api/getbooks') console.log(res) // Generally, the requested data is transferred to data this.bookList = res } } } </script>
script label content of Right component:
<script> export default { methods: { async postInfo() { const { data: res } = await this.$http.post('/api/post', { name: 'zs', age: 20 }) console.log(res) // The process of transferring data to data will not be demonstrated again } } } </script>
[disadvantages]: the code reusability of requesting data is poor. If different components need to request the same data, the request function must be written every time.
3, Encapsulate a module that gets axios and encapsulate the API for requesting data
1. Package axios module
At the same level as the src directory, create a utils folder to represent the tools used, and create a request JS file, which is the module that encapsulates axios. Whoever needs to use this root path to request data will import this module.
request.js file contents:
// Import axios import axios from 'axios' // Via axios The Create method creates an axios instance and receives it with request const request = axios.create({ // Specifies the root path of the request baseURL: 'http://www.liulongbin.top:3006' }) export default request
Usage (take Left component as an example):
<script> // Import request module import request from '@/utils/request.js' export default { data() { return { bookList: {} } }, methods: { async getInfo() { // Suppose a parameter needs to be passed. The parameter here is false. It is used for demonstration const { data: res } = await request.get('/api/getbooks', { params: { id: 1 } }) console.log(res) // Generally, the requested data is transferred to data this.bookList = res } } } </script>
[expansion] multiple axios modules can be encapsulated in a project. If multiple different request root paths are needed, each root path encapsulates a corresponding axios module, and then each module is different from each other and does not affect each other.
However, the problem of low code reusability is still not solved at this time. The request function will be written repeatedly. At this point, we encapsulate the code requesting data into an API module.
2. Package API module
At the same level as the src directory, create an API folder to represent the API written by yourself, and create a bookapi in it JS file, which is the module of encapsulated books. All API interfaces of book can be encapsulated into this module. Whoever needs to use this API interface will import this module.
bookAPI.js file contents:
// Import request module import request from '@/utils/request.js' // Export an interface function as needed export const getBookListAPI = function() { // Remember to return the promise object requested return request.get('/api/getbooks', { // Suppose you need to pass a parameter. The parameter here is false. It is used for demonstration params: { id: 1 } }) }
<script> // Import bookAPI on demand import { getBookListAPI } from '@/api/bookAPI.js' export default { data() { return { bookList: {} } }, methods: { async getInfo() { // Call getBookListAPI to request data const { data: res } = await getBookListAPI() console.log(res) // Generally, the requested data is transferred to data this.bookList = res } } } </script>
This is to realize the encapsulation of the request data interface and improve the reusability of the code.