itsource

AX 분리 방법Vuex 스토어로부터의 IOS 요구

mycopycode 2022. 8. 31. 22:51
반응형

AX 분리 방법Vuex 스토어로부터의 IOS 요구

매우 정상적인 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 요청을 다른 파일로 분리하여 내 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를 시도합니다.

import requests from './requests';

문제

내가 글을 쓰려고 할 때마다requests.GET_COMPANY_DETAILS();내 안에서getCompanyBasicInfo()의 메서드에 액세스 할 수 없는 액션requests.js파일.

에러 발생

Uncaught ReferenceError: GET_COMPANY_DETAILS is not defined콘솔로

내보내기 문제

쓰고 있으니까export default GET_COMPANY_DETAILSImport 시requests, 입니다.GET_COMPANY_DETAILS기능.

전화할 수 있게requests()직접적으로.

모든 가능성을 확인하려면 의 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);
        });
    }
}

스토어 관련 코드가 여전히 작업 범위 내에 있어야 합니다.

격리를 한 단계 더 밀어냅니다.

저는 하나의 책임 모듈을 만드는 데 도움이 되는 공리(중간 소프트웨어)와 공리소스(공리소스)에 대한 예를 들어 답을 썼습니다.

리소스 클래스 내에 엔드포인트 구성을 집중시키면서 미들웨어에서 오류를 처리할 수 있습니다.

Vuex 설명서의 권장 애플리케이션 구조에 따라 코드를 구성할 것을 권장합니다.

그렇게 하면 고민거리를 잘 분리할 수 있고, 당신의 가게.js는 멋지고 날씬해질 것입니다.

그런 다음 함수를 기본값으로 내보내는 대신 내보냅니다.향후, 복수의 함수를 export 할 수도 있습니다.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() {}

그럼, 를 사용하는 대신setTimeoutGET_COMPANY_DETAILSAxios 자체에서 약속을 반환한다.

예.

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

그리고 그 약속을 행동으로 옮긴다.

import { getCompanyDetails } from './requests';

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

언급URL : https://stackoverflow.com/questions/49639605/how-to-separate-axios-requests-from-a-vuex-store

반응형