Basic Edition Step 1: Configure AxiosFirst, create a Service.js, which stores the axios configuration and interceptors, and finally exports an axios object. I usually use elementUI more often, you can also use your own UI library here. import axios from 'axios' import { Message, Loading } from 'element-ui' const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment let loadingInstance = null //Here is loading //Use the create method to create an axios instance export const Service = axios.create({ timeout: 7000, // Request timeout baseURL: ConfigBaseURL, method: 'post', headers: { 'Content-Type': 'application/json;charset=UTF-8' } }) // Add request interceptor Service.interceptors.request.use(config => { loadingInstance = Loading.service({ lock: true, text: 'loading...' }) return config }) // Add response interceptor Service.interceptors.response.use(response => { loadingInstance.close() // console.log(response) return response.data }, error => { console.log('TCL: error', error) const msg = error.Message !== undefined ? error.Message : '' Message({ message: 'Network error' + msg, type: 'error', duration: 3 * 1000 }) loadingInstance.close() return Promise.reject(error) }) The specific interceptor logic depends on the specific business. I don't have any logic here, I just added a global loading. Step 2: Encapsulate the requestHere I create another request.js, which contains the specific request. import {Service} from './Service' export function getConfigsByProductId(productId) { return Service({ url: '/manager/getConfigsByProductId', params: { productId: productId } }) } export function getAllAndroidPlugins() { return Service({ url: '/manager/getAndroidPlugin ', method: 'get' }) } export function addNewAndroidPlugin(data) { return Service({ url: '/manager/addAndroidPlguin', data: JSON.stringify(data) }) } Of course, you can also encapsulate the URL again and put it in another file. I think this is meaningless and will increase the complexity. The main thing to pay attention to here is the naming problem. It is recommended to name it according to the function. For example, here I use request method + function or content + parameters. In this way, the name getConfigsByProductId is also very clear. Step 3: UseIn the vue component import {getAllAndroidPlugins,getConfigsByProductId,addNewAndroidPlugin} from '@/api/request.js' getAllAndroidPlugins() .then(res=>{ }) Global use in main.js import {Service} from '@/api/Service.js' Vue.prototype.$axios=Service Advanced versionWith the upgrade of vue cli, core-js\babel and other dependencies have also been upgraded. Now you can use async/await as you like. Therefore, this encapsulation is to upgrade the previous Promise to async await. First, it is still the same. Encapsulate axios first //Service.js import axios from 'axios' const ConfigBaseURL = 'https://localhost:3000/' //Default path, you can also use env to determine the environment //Use the create method to create an axios instance export const Service = axios.create({ timeout: 7000, // Request timeout baseURL: ConfigBaseURL, method: 'post', headers: { 'Content-Type': 'application/json;charset=UTF-8' } }) // Add request interceptor Service.interceptors.request.use(config => { return config }) // Add response interceptor Service.interceptors.response.use(response => { // console.log(response) return response.data }, error => { return Promise.reject(error) }) At this point you have obtained an axios object, and then I recommend a commonly used library, mainly used to handle async errors: await-to-js. The code is continued from above. import to from 'await-to-js' export function isObj(obj) { const typeCheck = typeof obj!=='undefined' && typeof obj === 'object' && obj !== null return typeCheck && Object.keys(obj).length > 0 } export async function _get(url, qs,headers) { const params = { url, method: 'get', params: qs ? qs : '' } if (headers) { params.headers = headers } const [err, res] = await to(Service(params)) if (!err && res) { return res } else { return console.log(err) } } When encapsulating get, you only need to consider parameter, use await-to-js to capture errors during await, return data only when successful, and use the interceptor when an error occurs. export async function _get(url, qs,headers) { const params = { url, method: 'get', params: isObj(qs) ? qs : {} } if (isObj(headers)) {params.headers = headers} const [err, res] = await to(Service(params)) if (!err && res) { return res } else { return console.log(err) } } This is the post I packaged export async function _post(url, qs, body) { const params = { url, method: 'post', params: isObj(qs) ? qs : {}, data: isObj(body) ? body : {} } const [err, res] = await to(Service(params)) if (!err && res) { return res } else { return console.log(err) } } It can be directly introduced when used, or it can be encapsulated multiple times //a.vue <script> import{_get}from './Service' export default{ methods:{ async test(){ const res = await _get('http://baidu.com') } } } </script> The above is the details of several methods of Vue encapsulating Axios. For more information about Vue encapsulating Axios, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Docker Swarm from deployment to basic operations
>>: Centos7.5 installs mysql5.7.24 binary package deployment
This article example shares the specific code of ...
Table of contents Slots What are slots? Slot Cont...
I have written many projects that require changin...
The installation of MySQL 5.7 on Ubuntu 1804 is i...
Comments and messages were originally a great way...
question: In some browsers, such as 360 browser...
In the page, external files such as js, css, etc. ...
background: I have done a project before, which r...
After half an hour of trying to pull the MySQL im...
1. Command Introduction The chkconfig command is ...
illustrate This article was written on 2017-05-20...
Correspondence between flutter and css in shadow ...
When using vue to develop projects, the front end...
What is DOM? With JavaScript, you can reconstruct...
Docker is becoming more and more mature and its f...