让我们先看看目录结构

axios.js主要对axios的进行封装

import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';

const queryStringFormat = data => qs.stringify(data);

const config = {
  headers: {
    'Content-Type': 'application/json',
  },
  transformRequest: [queryStringFormat],
};
// eslint-disable-next-line no-underscore-dangle
const _axios = axios.create(config);

_axios.interceptors.request.use(
  config => config,
  error => Promise.reject(error),
);

_axios.interceptors.response.use(
  response => response,
  error => error.response,
);

// eslint-disable-next-line func-names
Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      },
    },
    $axios: {
      get() {
        return _axios;
      },
    },
  });
};

Vue.use(Plugin);

export default _axios;

apiList.js接口的url配置

export default {
  login: '/mvc/mobile/api/login',
  trade: {
    list: '/mvc/mobile/api/bizcircle/list',
    cityList: '/mvc/mobile/api/bizcircle/city/list',
    catList: '/mvc/mobile/api/bizcircle/cat/list',
  },
  course: {
    getMenus: '/mvc/mobile/api/tr/course/categoryMenu',
    getCourseList: '/mvc/mobile/api/tr/course/courseList',
    getDetail: '/mvc/mobile/api/tr/course/detail',
    courseware: '/mvc/mobile/api/tr/course/courseware',
    courseLearn: '/mvc/mobile/api/tr/course/courseLearning',
    courseFinish: '/mvc/mobile/api/tr/course/finished',
    courseList: ' /mvc/mobile/api/tr/course/bsm/courseList',
  },
  sales: {
    getmy: '/mvc/mobile/api/sellout/findMyProductGroup',
    getMonthQuery: '/mvc/mobile/api/sellout/thirdMonthQuery',
    getMonthWeekQuery: '/mvc/mobile/api/sellout/thirdMonthWeekQuery',
    getthirdMonthWeekProductCatQuery: '/mvc/mobile/api/sellout/thirdMonthWeekProductCatQuery',
    getthirdMonthWeekListProductCatQuery: '/mvc/mobile/api/sellout/thirdMonthWeekListProductCatQuery'
    // mobile/api/sellout/thirdMonthWeekListProductCatQuery
  }
};

BaseService.js配置axios的post get等请求方式

// import qs from 'qs';
import axios from '../axios';
import API from '../api';

// const queryStringFormat = data => qs.stringify(data, { indices: false });

export default class {
  constructor() {
    this.API = API;
  }

  // eslint-disable-next-line class-methods-use-this
  async get(url, data = {}) {
    let result = await axios.get(url, { params: data });
    try {
      result = result.data;
    } catch (error) {
      result.data = {
        result: false,
        message: error.toString(),
      };
    }
    return result;
  }

  // eslint-disable-next-line class-methods-use-this
  async post(url, data = {}, headers = {}, params = {}, transformRequest) {
    let result = {};
    // headers.token = localStorage.walkman_token;
    try {
      result = await axios(
        {
          method: 'POST',
          url,
          data,
          params,
          headers,
          transformRequest,
        },
      );
      result = result.data;
    } catch (err) {
      result = {
        success: false,
        message: err.toString(),
        returnCode: err.status,
      };
    }
    return result;
  }
}

services除BaseService.js以外的其他文件继承 BaseService.js 并且配置接口参数

import BaseService from './BaseService';

export default class AuthService extends BaseService {
  async addWord(data) {
    const url = this.API.sensitive.addWord;
    const result = await this.post(url, {}, {}, data);
    return result;
  }

  async pagingAllWords(data = {}) {
    const url = this.API.sensitive.pagingAllWords;
    const result = await this.post(url, {}, {}, data);
    return result;
  }

  async findWord(data = {}) {
    const url = this.API.sensitive.findWord;
    const result = await this.post(url, {}, {}, data);
    return result;
  }

  async deleteWord(data = {}) {
    const url = this.API.sensitive.deleteWord;
    const result = await this.post(url, {}, {}, data);
    return result;
  }

  async updateConfig(data = {}, headers) {
    const url = this.API.set.updateConfig;
    const transformRequest = [function (data) {
      data = JSON.stringify(data);
      return data;
    }];
    const result = await this.post(url, data, headers, {}, transformRequest);
    console.log(data, result, 'result');
    return result;
  }

  async BulletinBoard(data = {}) {
    const url = this.API.set.BulletinBoard;
    const result = await this.post(url, {}, {}, data);
    return result;
  }

  // 上传图片
  async getPicture(file, headers, parase = {}) {
    const formdata = new FormData();
    formdata.append('picture', file.picture);
    const url = this.API.set.getPicture;
    const transformRequest = [function (data) {
      // data = JSON.stringify(data);
      return data;
    }];
    const result = await this.post(url, formdata, headers, parase, transformRequest);
    return result;
  }

  // 公告栏上传图片
  async BulletinBoardPicture(file, headers, parase = {}) {
    const formdata = new FormData();
    formdata.append('picture', file.picture);
    const url = this.API.set.BulletinBoardPicture;
    const transformRequest = [function (data) {
      // data = JSON.stringify(data);
      return data;
    }];
    const result = await this.post(url, formdata, headers, parase, transformRequest);
    return result;
  }

  async saveConfig(data = {}, headers) {
    const url = this.API.set.saveConfig;
    const transformRequest = [function (data) {
      data = JSON.stringify(data);
      return data;
    }];
    const result = await this.post(url, data, headers, {}, transformRequest);
    console.log(data, result, 'result');
    return result;
  }

  async deleteConfig(data = {}) {
    const url = this.API.set.deleteConfig;
    const result = await this.post(url, {}, {}, data);
    return result;
  }
}

最后我们回到index.js将方法绑定到原型上

import BaseService from './services/BaseService';
import AuthService from './services/AuthService';
import SensitiveService from './services/SensitiveService'
import apiList from './api';

class Service {
  constructor() {
    this.base = new BaseService();
    this.auth = new AuthService();
    this.sensitive = new SensitiveService();
    this.API = apiList;
  }
}

const serviceInstance = new Service();

const services = {
  install(Vue, name = '$api') {
    Object.defineProperty(
      Vue.prototype,
      name,
      { value: serviceInstance },
    );
  },
  ...serviceInstance,
};

export default services;

然后main.js引入并且使用

import services from './service';
Vue.use(services);

最后调用接口

   const result = await this.$api.auth.auditBarrage({
        id: _id,
        barrageStatus: type,
      });

Lifelong learning lifelong benefit