programing

Axios를 사용하여 Vuex 스토어에서 데이터 검색

goodsources 2023. 1. 3. 21:48
반응형

Axios를 사용하여 Vuex 스토어에서 데이터 검색

나는 내 질문에 대한 가능한 답을 찾아봤지만 더 이상 제안할 수 없었다.

제 프로젝트의 구조는 다음과 같습니다.PoolMainPage를 가지고 있습니다.이 페이지에는, 다음의 정보를 표시할 수 있습니다.activePool물건.내부PoolMainPage서브페이지에 직접 접속하는 옵션이 있습니다).TeamSelector그리고.PoolStandings의 정보도 필요합니다.activePool물건.

activePool 개체가 Vuex 저장소의 끝점에서 가져옵니다.그 코드는 다음과 같습니다.

const actions = {  
  getActivePool({ commit }) {
    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      withCredentials: true
    }
    const activePoolId = localStorage.getItem('activePoolId')
    if (activePoolId) {
      return axios.get('/pools/pool-information?poolId=' + activePoolId, config)
        .then((response) => {
          commit('SET_ACTIVE_POOL', response.data)
          return response
        })
        .catch((error) => {
          return Promise.reject(error)
        })
    } else {
      commit('SET_ACTIVE_POOL', null);
      return;
    }
  }
}

엔드포인트는 자신의 작업을 수행하고 다음 명령을 반환합니다.activePool물건.인마이PoolMainPagecomponent(및 서브컴포넌트) 이 액션을 호출하고 다음 명령을 사용하여 객체를 가져옵니다.

created() {
    if (!this.$store.getters.activePool) {
      this.$store.dispatch("getActivePool");
    }
  },

페이지가 새로 고쳐질 때마다 엔드포인트가 호출되지 않도록 체크를 추가했습니다.activePool는 이미 설정되어 있습니다.실제로 로드하려면activePool컴포넌트로 변환하여 계산 속성을 작성했습니다.

computed: {
    activePool() {
      return this.$store.getters.activePool;
    },
  },

이 모든 것은 엔드포인트가 데이터를 반환했을 때 작동하지만 그 전에 다른 계산 속성에 오류가 표시되며, 이 속성은 에 의존합니다.activePool오브젝트:

maxToSpend() {
      return this.activePool.inGameBudget;
    },

질문 1: 다음 사항을 확실하게 하려면 어떻게 해야 합니까?maxToSpend계산은 다음 시간까지 이루어지지 않습니다.activePool정말 세팅이 되나요?나는 단순히 수표를 추가할 수 있다.if (this.activePool) {모든 계산된 속성에 대해 이 작업을 수행해야 합니다.

질문 2: 이것이 가능한지 모르겠습니다만, 어떻게 하면 이 코드를 추가할 필요가 없는지를 확인할 수 있을까요?activePool엔드포인트에서 생성된 각 컴포넌트 내에서 계산된 속성을 사용하여 가져옵니다.TeamSelector그리고.PoolStandings?

모든 도움/제안 감사합니다!불명확하거나 추가 정보가 필요한 사항이 있으면 알려주세요.

감사합니다!

제로엔

activePool이 실제로 설정될 때까지 maxToSpend가 계산되지 않도록 하려면 어떻게 해야 합니까?

기본적으로 당신은 그것을 할 수 없습니다.계산된 속성은 구성 요소 생성 직후에 계산됩니다.라이프 사이클 다이어그램을 참조해 주세요.계산된 속성은 Init 주입 및 반응도 상태에서 계산됩니다.

(this.activePool) {의 경우 체크만 추가하면 됩니다만, 계산한 모든 속성에 대해 체크해야 합니다.

Getters를 사용하는 경우:

state: {
  ...
},
getters: {
  maxToSpend: state => {
    if (!state.activePool) return
    return state.activePool.inGameBudget
  }
},
actions: {
  ...
}

그 후 다음과 같이 사용할 수 있습니다.

computed: {
  maxToSpend () {
    return this.$store.getters.maxToSpend
  }
}

이것이 가능한지 알 수 없지만 엔드포인트에서 activePool을 가져오기 위해 코드를 추가할 필요가 없는지 확인하고 작성한 각 컴포넌트 내에서 계산된 속성을 사용하여 가져올 수 있는 방법은 다음과 같습니다.Team Selector와 Pool Septions?

기본적으로 아니다.그러나 TeamSelector와 PoolSeptions가 모두 공통의 부모(PoolMainPage?)를 가지고 있는 경우 해당 부모에서 한 번만 호출할 수 있습니다.

필요한 페이지마다 강제적인 액션을 명시적으로 송신하는 것도 나쁘지 않다고 생각합니다.

중첩된 속성에 액세스할 때 오류를 방지하기 위해 activePool getter를 마운트할 수 있습니다.예를 들어 다음과 같습니다.

// in getters.js

const activePool = (state) => ({
  ...state.activePool,
  maxToSpend: state.activePool && state.activePool.inGameBudget,
})

activePool.inGameBudget을 선택합니다. 해서 할 수 되었습니다.this.activePool.inGameBudget;.vue이 에러는 표시되지 않습니다.

언급URL : https://stackoverflow.com/questions/59884632/retrieve-data-from-vuex-store-using-axios

반응형