Use axios, in Vue to put all request methods in the same JS

I have seen in a Vue project that all the axios request methods are in one js file, and you can create multiple js files to manage these methods. Now I want to use them in the project, but I can"t write them out. How should I write it, please? It seems that there is an index.js file that introduces other js files and then exposes them.

Aug.16,2021

give you a reference

order.js

import axios from 'axios'

let base = '/api/v1/order'

const order = {
  getList  : params => axios.get(`${base}`, {params}),
  getDetail: id     => axios.get(`${base}/${id}`),
  delete   : id     => axios.delete(`${base}/${id}`),
  add      : params => axios.post(`${base}`, params),
  update   : params => axios.put(`${base}/${params.id}`, params),
}

export default order

index.js

import orderModel from './order'

export {
  orderModel
}

is it something like this, write a js file, such as api.js,

import axios from 'axios';
const http = axios.create({ baseURL: 'http://xxx.yyy.zzz:3000/' });
export default {
    getXXX(para) {
        return http.get(`url/${para}`)
    },
    setYYY() {
        return http.post('other/url');
    }
};

when you use it, such as in vuex store, you can go like this:

import api from './api';
actions: {
    setXXX({ commit }, para) {
        return api.getXXX(para).then(({ data }) => {
            commit('XXX', data);
        });
    }
}

of course, if you can't finish writing a js file, you can write multiple js, in one directory, export them all with one index.js, and add one more level when you use them, such as api.moudleA.getXXX, api.moudleB.setYYY.

Menu