programing

서버에서 Vuex + Vue 풀 상태를 1회만 실행

copyandpastes 2022. 8. 23. 22:55
반응형

서버에서 Vuex + Vue 풀 상태를 1회만 실행

History 뷰에서 Vuex 액션을 호출하여 백엔드 서버에서 이력을 풀다운합니다.created()계산 함수를 사용하여 데이터를 이력 테이블에 전달합니다.history()이력 모듈 상태에 액세스 합니다.

문제는 [History]뷰로 돌아갈 때마다 액션을 호출하기 위해 서버에 대한 새로운 요구가 발행된다는 것입니다.created().

뷰에 처음 액세스할 때 콜이 이루어지도록 설정하고 이 뷰에 대한 다음 방문 시 이력 상태에 의존하도록 설정하려면 어떻게 해야 합니까?

역사.표시하다

<script>
import { mapActions } from "vuex";
export default {
  name: "History",
  data() {
    return {
        // data
    };
  },
  methods: {
    ...mapActions(["fetchHistory"]),
    refresh() {
        this.fetchHistory() 
  },
  computed: {
    history() {
      return this.$store.state.history.records;
    },
  },
  created() {
    this.refresh();
  },
};
</script>

historyModule.js

async fetchHistory({commit}){
    await axios.get('api/history')
        .then((response) => {
            commit('setHistory', response.data)
            return Promise.resolve();
        })
        .catch((error) => {
            commit('setHistory', [])
            return Promise.reject(error)
        })
}

한다면history.records는, 액션을 디스패치 하기 전에 길이를 확인할 수 있는 어레이입니다.

created() {
  if(!this.$store.state.history.records.length) this.refresh();
},

이 패턴이 여러 구성 요소에서 작동하도록 하려면 생성된 후크가 아닌 Vuex 작업에 동일한 동작을 추가할 수 있습니다.이렇게 하면 모든 Vuex 동작이 스토어 코드 내에 유지됩니다.

언급URL : https://stackoverflow.com/questions/69499707/vuex-vue-pull-state-from-server-just-once

반응형