1. RequirementsWhen using the Vue.js framework to develop front-end projects, ajax requests to the server interface are often sent. During the development process, axios needs to be further encapsulated to facilitate its use in the project. 2. Vue project structureCreate a Vue project locally with the following directory structure:
Create an http directory in the Vue project as the management directory of axios. There are two files in the http directory, namely
3. Code ExamplesThe code of the /http/api.js file is as follows: export default { 'users_add': '/users/add', 'users_find': '/users/find', 'users_update': '/users/update', 'users_delete': '/users/delete' } The code of the /http/index.js file is as follows: import axios from 'axios' import api from './api' //Create an axios instance object let instance = axios.create({ baseURL: 'http://localhost:3000', //server address timeout: 5000 //default timeout duration}) //Request interceptor instance.interceptors.request.use(config=>{ //Write the code for request interception here, which is generally used to pop up the loading window console.log('Requesting...') return config },err=>{ console.error('Request failed',err) }) //Response interceptor instance.interceptors.response.use(res=>{ //Process the response data here console.log('Request successful!') return res //The returned object will be passed to the response object of the request method},err=>{ // Response error handling console.log('Response failed!', err) // return Promise.reject(err); }) //Encapsulate axios request method, parameter is configuration object //option = {method,url,params} method is request method, url is request interface, params is request parameter async function http(option = {}) { let result = null if(option.method === 'get' || option.method === 'delete'){ //Handle get and delete requests await instance[option.method]( api[option.url], {params: option.params} ).then(res=>{ result = res.data }).catch(err=>{ result = err }) }else if(option.method === 'post' || option.method === 'put'){ //Process post and put requests await instance[option.method]( api[option.url], option.params ).then(res=>{ result = res.data }).catch(err=>{ result = err }) } return result } export default http Import the encapsulated /http/index.js file into the main.js entry file. The sample code is as follows: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import http from './http' Vue.config.productionTip = false Vue.prototype.$http = http Vue.use(Elementui) new Vue({ router, store, render: h => h(App) }).$mount('#app') Test the axios request in the App.vue root component. The sample code is as follows: <template> <div> <button @click="getDate">Send request</el-button> </div> </template> <script> export default { methods: { getDate(){ this.$http({ method: 'get', url: 'users_find' }).then(res=>{ console.log(res) }) } } } </script> There needs to be an http://localhost:3000/users/find interface here, otherwise the request will fail! 4. Effect DemonstrationStart the Vue project and access the address of the Vue project in the browser. My address is http://localhost:8080. Click the button to send the request. The result is shown in the figure below. At this point, a simple axios encapsulation has been completed in the Vue project. You can also encapsulate axios according to your actual needs. This article is just for reference. This is the end of this article about how to encapsulate axios (unified management of http requests) in Vue projects. For more relevant Vue encapsulation axios management http request content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of InnoDB storage files in MySQL
>>: Detailed explanation of EXT series file system formats in Linux
The default ssh remote port in Linux is 22. Somet...
WEB development mainly consists of two interactio...
Generate a certificate chain Use the script to ge...
Engineering Structure The project is divided into...
The EXPLAIN statement is introduced in MySQL quer...
Why is NULL so often used? (1) Java's null Nu...
Make a nice flip login and registration interface...
The previous article has installed the docker ser...
For detailed documentation on installing the comp...
1. Introduction I wrote an article before: The pr...
Table of contents First, configure package.json T...
1. SHOW PROCESSLIST command SHOW PROCESSLIST show...
In order to express the deep condolences of peopl...
1. Background execution Generally, programs on Li...
question The code has no prompt: Many non-front-e...