簡體   English   中英

如何從Vuex商店中分離AXIOS請求

[英]How to separate AXIOS requests from a Vuex store

我有一個非常正常的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';

問題

每當我嘗試寫requests.GET_COMPANY_DETAILS(); 在我的getCompanyBasicInfo()操作中,我無法訪問requests.js文件中的方法。

我得到的錯誤

Uncaught ReferenceError: GET_COMPANY_DETAILS is not defined在控制台中Uncaught ReferenceError: GET_COMPANY_DETAILS is not defined

出口問題

由於您使用export default GET_COMPANY_DETAILS ,因此在導入requests ,它是GET_COMPANY_DETAILS函數。

所以你可以直接調用requests()

有關export ,請參閱MDN文檔以查看所有可能性。

如何導出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');
    }
};

您可以像我一樣導出default 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的例子寫了一個答案 ,這有助於創建單一責任模塊。

您可以處理中間件中的錯誤,同時將端點配置集中在資源類中。

我建議您根據Vuex文檔中建議的應用程序結構來構建代碼。

這將為您提供良好的關注點分離,讓您的store.js變得更好,更精益。

然后,導出函數而不是默認導出它。 將來,您可能希望從requests.js導出多個函數。

例如

import axios from 'axios';

export function getCompanyDetails() {
  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);
};

export function someOtherApiMethod() {}

然后,不是在GET_COMPANY_DETAILS中使用setTimeout ,而是從Axios本身返回promise。

例如

 export function getCompanyDetails() {
    return axios
        .get('http://localhost:3000/companies/show/trade key egypt')
        .then(res => res.data)
};

然后,在您的操作中使用promise

import { getCompanyDetails } from './requests';

actions: {
    getCompanyBasicInfo: context => {
        getCompanyDetails().then(() => {
            // commit your mutations
        });
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM