当前位置:首页 > 操作系统 > Ios

javascript-如何从Vuex存储区分离AXIOS请求

我有一个非常普通的Vuex存储文件,下面是代码:

//store.js
import Vue from 'vue';
import Vuex from 'vuex';


Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    loading: true,
    companyBasicInfo: [

    ]
  },
  mutations: {
    getCompanyBasicInfo: (state, res) => {
      state.companyBasicInfo.push(res);
    },
    changeLoadingStatue: (state, loading) => {
      state.loading = loading;
    }
  },
  actions: {
    getCompanyBasicInfo: context => {
// HERE IS MY AXIOS REQUESTS
    }
  }
});

我在getCompanyBasicInfo()操作中编写了axios请求,并且一切正常.

我想做的事

将我的AXIOS请求分离到另一个文件中,然后仅在store.js文件中调用它们即可,以减少store.js文件.

我尝试过的

我试图创建一个名为requests.js的文件,并在其中编写以下代码:

import axios from 'axios';

export default GET_COMPANY_DETAILS = () => {
  setTimeout(() => {
    axios.get('http://localhost:3000/companies/show/trade key egypt').then((res) => {
      context.commit('getCompanyBasicInfo', res.data);
      context.commit('changeLoadingStatue', false);
    }).catch(e => {
      console.log(e);
    });
  }, 3000);
};

然后尝试将它们导入到我的store.js文件中

import requests from './requests';

问题

每当我尝试编写请求时.GET_COMPANY_DETAILS();在我的getCompanyBasicInfo()操作中,我无法访问request.js文件中的方法.

我得到错误

未捕获的ReferenceError:控制台中未定义GET_COMPANY_DETAILS

解决方法:

出口问题

由于您使用的是导出默认的GET_COMPANY_DETAILS,因此在导入请求时,它就是GET_COMPANY_DETAILS函数.

因此,您可以直接调用request().

请参阅MDN documentation on export以查看所有可能性.

如何导出API

话虽如此,导出API的正确方法是:

// api.js
import axios from 'axios';

// create an axios instance with default options
const http = axios.create({ baseURL: 'http://localhost:3000/' });

export default {
    getCompanyDetails(tradeKey) {
        // then return the promise of the axios instance
        return http.get(`companies/show/${tradeKey}`)
            .catch(e => {
                // catch errors here if you want
                console.log(e);
            });
    },
    anotherEndpoint() {
        return http.get('other/endpoint');
    }
};

您可以像我一样导出默认API,甚至可以导出命名导出和默认导出.

export function getCompanyDetails(tradeKey){ /*...*/ }
export default { getCompanyDetails }

然后,在您的商店中:

import api from './api';

// ...

actions: {
    getCompanyBasicInfo({ commit }, key) {
        // It's important to return the Promise in the action as well
        return api.getCompanyDetails(key).then(({ data }) => {
            commit('getCompanyBasicInfo', data);
            commit('changeLoadingStatue', false);
        });
    }
}

与商店相关的代码仍需要放在您的操作之内.

进一步推动隔离

我在axios-middlewareaxios-resource上编写了带有示例的an answer,这有助于创建单一职责模块.

您可以处理中间件中的错误,同时将端点配置集中在资源类中.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!