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_DETAILS
Import 시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() {}
그럼, 를 사용하는 대신setTimeout
에GET_COMPANY_DETAILS
Axios 자체에서 약속을 반환한다.
예.
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
'itsource' 카테고리의 다른 글
C/C++에서 사람들이 하는 부당한 가정을 설명하기 위한 교육 도구에는 무엇이 있습니까? (0) | 2022.08.31 |
---|---|
CMake에서 컴파일러가 Clang인지 테스트하려면 어떻게 해야 하나요? (0) | 2022.08.31 |
Alarm Manager 예시 (0) | 2022.08.31 |
Safari 폭(%) 계산이 잘못됨(부모로부터 1px 필러). (0) | 2022.08.31 |
Vuex 상태의 어레이 항목 복제(Socket.io 사용) (0) | 2022.08.31 |