1. Install axios

npm i axios --save
Copy the code

2. Wrap axios

import axios from 'axios'

export default function ajax(url = ' ', params = {}, type = 'GET') {
    let promise;
    return new Promise((resolve, reject) => {
        if (type.toUpperCase() === 'GET') {
            let paramstr = ' '; // Splice parameters such as name='tom'& age ='12'
            Object.keys(params).forEach(key => {
                paramstr += key + "=" + params[key] + '&'}) // If there are arguments, the last superfluous & is truncatedif(paramstr) {paramstr = paramstr.substring(0, paramstr.length)} // Obtain the correct request address URL +='? '+ paramstr // Make a get request. Promise = axios.get(url)}else if (type.toUpperCase() === 'POST') {// Make a post request. Promise = axios.post(url, Then ((response) => {resolve(response.data)}). Catch (err => {reject(err)})})}Copy the code

3. Unified interfaces

import ajax from './ajax.js'
const BASE_URL = 'http://xxxxxxx export const getHomeData = () => ajax(BASE_URL + '/api/homeApi')
Copy the code

4. Used in components

<template> <div>home page </div> </template> <script> //1 Start by referring to the API import {getHomeData} from"@/service/api.js";
export default {
  data() {
    return {};
  },
  createdGetHomeData (). Then (res => {console.log(res); }); }}; </script> <style lang="less" scoped>
</style>
Copy the code