Vuex를 사용하여 API를 호출하는 올바른 방법은 무엇입니까?
저는 Vuex에 Vue Webpack 앱을 가지고 있습니다(두 앱 모두 Ember 세계에서 온 지 얼마 안 되었습니다).현재 다음과 같은 두 개의 파일로 vue-resource를 사용하도록 설정되어 있습니다.
/src/store/api.module
import Vue from 'vue';
import { store } from './store';
export default {
get(url, request) {
return Vue.http
.get(store.state.apiBaseUrl + url, request)
.then(response => Promise.resolve(response.body))
.catch(error => Promise.reject(error));
},
post(url, request) {
return Vue.http
.post(store.state.apiBaseUrl + url, request)
.then(response => Promise.resolve(response))
.catch(error => Promise.reject(error));
},
// Other HTTP methods removed for simplicity
};
그런 다음 위의 api.js 파일을 다음과 같이 /src/store/store.js 파일로 Import합니다.
import Vue from 'vue';
import Vuex from 'vuex';
import Api from './api';
Vue.use(Vuex);
// eslint-disable-next-line
export const store = new Vuex.Store({
state: {
apiBaseUrl: 'https://apis.myapp.com/v1',
authenticatedUser: null,
},
mutations: {
/**
* Updates a specific property in the store
* @param {object} state The store's state
* @param {object} data An object containing the property and value
*/
updateProperty: (state, data) => {
state[data.property] = data.value;
},
},
actions: {
usersCreate: (context, data) => {
Api.post('/users', data)
.then(response => context.commit('updateProperty', { property: 'authenticatedUser', value: response.body }))
// eslint-disable-next-line
.catch(error => console.error(error));
},
},
});
새 사용자를 생성해야 할 경우,this.$store.dispatch('usersCreate', { // my data });내 컴포넌트에 있습니다.이 조작은 정상적으로 동작합니다만, 몇개의 문제가 있습니다.
- 토스트 메시지 등을 표시하기 위해 컴포넌트에서 문제를 캡처할 수 없습니다.AJAX 콜이 정상적으로 통과했는지도 확인할 수 없습니다.
- API가 많으면 store.js 파일에 많은 액션을 써야 하는데 이상적이지 않습니다.물론 HTTP 메서드나 URL 등을 받아들이는 표준 액션을 작성하여 호출할 수도 있지만 이것이 좋은 방법인지 잘 모르겠습니다.
어떻게 하면 좋을까요?액션을 디스패치하는 컴포넌트에서 AJAX 장애/성공 상태를 확인하려면 어떻게 해야 합니까?Vuex를 사용할 때 API 호출을 하는 가장 좋은 방법은 무엇입니까?
당신의 행동은 약속을 반환해야 합니다.현재 코드가 호출만 합니다.Api.postVuex는 루프에서 벗어납니다.Composing Actions에 대해서는 Vuex 문서의 예를 참조하십시오.
약속을 반환하면 액션 발신자는 다음 명령을 따를 수 있습니다.then()체인:
this.$store.dispatch('usersCreate').then(() => {
// API success
}).catch(() => {
// API fail
});
자신의 행동을 정리하는 것에 대해서는, 모든 것을 자신의 행동에 넣을 필요는 없습니다.store.js파일. Vuex는 모듈/네임스페이스를 지원합니다.https://vuex.vuejs.org/en/modules.html
언급URL : https://stackoverflow.com/questions/48505230/what-is-the-right-way-to-make-api-calls-with-vuex
'programing' 카테고리의 다른 글
| v-card 내부의 bootstrap-vue v-module이 'bootstrap'을 렌더링함 (0) | 2022.08.17 |
|---|---|
| 커스텀 Laravel Nova 툴에서는 확인 다이얼로그를 어떻게 사용합니까? (0) | 2022.08.17 |
| Vuex getter의 옵서버에서 값 가져오기 (0) | 2022.08.17 |
| 왜 일부 커널 프로그래머들은 루프 중에 단순 대신 goto를 사용하는가? (0) | 2022.08.11 |
| nuxt plugins 글로벌 메서드의 typescript 정의에 유형이 있습니까? (0) | 2022.08.11 |