programing

Vuex - http 서버에서 스토어 데이터를 로드/초기화하는 시기

copyandpastes 2022. 8. 23. 23:09
반응형

Vuex - http 서버에서 스토어 데이터를 로드/초기화하는 시기

올바르게 표시하기 위해서 리모트로 취득할 필요가 있는(http get call) 데이터를 메뉴바에 표시합니다.앱이 로딩되었을 때 스토어가 아직 초기화되지 않았습니다.어디서 하면 되죠?

이게 제가 지금 가지고 있는 거예요. nodeInfo데이터를 가져오지 않는 한 빈 개체입니다.

항법 부품

<template>
  <nav class="navbar" role="navigation" aria-label="main navigation">
    ...
      <div class="navbar-end">
        <span class="navbar-item">
          <div v-if="nodeInfo.latestSolidSubtangleMilestoneIndex">
            {{nodeInfo.latestSolidSubtangleMilestoneIndex}} / {{nodeInfo.latestMilestoneIndex}}
          </div>
          <div v-else>
            Node seems offline!
          </div>
        </span>
      </div>
    </div>
  </nav>
</template>

<script>
  import {mapGetters} from 'vuex';

  export default {
    name: 'Menu',
    computed: {
      ...mapGetters(['nodeInfo']) // Only the getters, no actions called to initialize them.
    }
  };
</script>

<style scoped>

</style>

스토어:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import axios from 'axios';

const iri_ip = '192.168.1.199';
const iri_port = '14265';

const state = {
  token: null,
  loading: false,
  nodeInfo: {}
};

const mutations = {
  SET_NODE_INFO(state, info) {
    state.nodeInfo = info;
  }
};

const actions = {
  fetchNodeInfo({commit}) {
    axios(createIriRequest('getNodeInfo')).then(response => {
      console.log(response.data);
      commit('SET_NODE_INFO', response.data);
    });
  }
};

const getters = {
  token: state => state.token,
  loading: state => state.loading,
  nodeInfo: state => state.nodeInfo
};

const loginModule = {
  state,
  mutations,
  actions,
  getters
};

function createIriRequest(command) {
  return {
    url: `http://${iri_ip}:${iri_port}`,
    data: {'command': command},
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      'X-IOTA-API-Version': '1'
    }
  };
}

export default new Vuex.Store({
  modules: {
    loginModule
  }
});

그 이름은 현재로선 별로 말이 되지 않는다.그러나 메뉴 컴포넌트의 create() 메서드에서 "actions"를 호출해야 합니까?그건 좀 이상할 것 같아.저희 가게가 트리거할 필요 없이 어떻게든 첫 번째 http 콜을 할 수 있다면 좋을 것 같습니다.create() 부분에서 그런 동작을 어떻게 호출해야 하는지조차 모릅니다.

vue.discle diagram(vue.discle diagram)의 라이프 사이클 다이어그램을 참조해 주세요.https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram 에서는 라이프 사이클 훅을 참조해 주세요.스토어 디스패치 방법을 언제 어디에 추가해야 하는지 알 수 있습니다. this.$store.dispatch('fetchNodeInfo')

요약:

  • 작성된 후크:인스턴스가 생성되어 모든 데이터 관찰, 계산된 속성, 메서드, 워치/이벤트 콜백이 설정되었지만 $el 속성을 아직 사용할 수 없습니다.

  • 장착 후크:Vue 인스턴스가 마운트되었습니다. 여기서 el은 새로 생성된 VM으로 대체됩니다.$el. el은 새로운 Vue({...})를 통한 인스턴스 작성입니다.

독서의 즐거움을 위해:

@버트가 옳았다.컴포넌트의 created() 메서드에 디스패치 방식을 추가했습니다.

export default {
    name: 'Menu',
    created() {
      this.$store.dispatch('fetchNodeInfo');
    },
...
}

언급URL : https://stackoverflow.com/questions/50785748/vuex-when-to-load-initialize-store-data-from-http-server

반응형