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
1. Same IP address, different port numbers Virtua...
I recently started learning Linux. After reading ...
Table of contents 1. Environmental Installation 2...
The installation tutorial of mysql 5.7.19 winx64 ...
Use JOIN instead of sub-queries MySQL supports SQ...
Prerequisites 1. Docker has been installed on the...
We know that in general, a function must be calle...
Duplicate form submission is the most common and ...
The cascading drop-down menu developed in this ex...
Table of contents Initialize the project Writing ...
Tomcat server is a free and open source Web appli...
When we learn HTML, the image tag <img> int...
During the development process, if garbled charac...
1 Download MySQL8 from the official website and i...
Question 1: When entering net start mysql during ...