First install axios
npm install axios --save
Create a new ajax.js file to encapsulate axios, expose encapsulated code functions, and call them on other pages
import axios from 'axios' import qs from 'qs'//Serialized string import {MessageBox} from 'element-ui'//Introducing elementUI components import router from "../router.js"; axios.defaults.withCredentials = true; //Let ajax carry cookie s axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'//Setting the request header export default function ajax(url, data = {}, type = 'GET') { if (data === {}) { data = { "t": new Date().getTime() } } return new Promise(function(resolve, reject) { // Execute asynchronous ajax requests let promise if (type === 'GET') { // Prepare url query parameter data let dataStr = '' //Data mosaic string Object.keys(data).forEach(key => { dataStr += key + '=' + data[key] + '&' }) if (dataStr !== '') { dataStr = dataStr.substring(0, dataStr.lastIndexOf('&')) url = url + '?' + dataStr + '&_=' + new Date().getTime() } // Send get request promise = axios.get(url, data) } else { // Send a post request promise = axios.post(url, qs.stringify(data)) } promise.then(function(response) { // A successful call to resolve() resolve(response.data) if (response.data.status != 'success') { MessageBox.alert(response.data.msg, 'Error prompt', { confirmButtonText: 'Determine', type: 'error' }); } }).catch(function(error) { //Failed to call reject() if (error && error.response) { if (error.response.data.message === 'User not logged in') { router.push('/login') } } reject(error) }) }) }
Create a new api.js file, call axios, set up the interface and expose it (interface is unified in a file, easy to manage)
import ajax from './ajax'//Introducing packaged axios export const Constant name = (parameter)=>ajax(url,{parameter},'Method name') //Example: export const DETAIL = (index, id) => Ajax ('http://baidu.com/hhh/detail', {index, id})
On pages where the interface is needed, the interface is introduced and invoked
//Import interface import {DETAIL} from "../../api/api.js" //Calling interface async init(){ let result = await DETAIL(index,id) }
This article uses part of es6. If you don't understand it, you can take a look at it. Introduction to Ruan Yifeng ES6
There is also a good article on async await. You can take a look at it. async await asynchronism