programing

Vuex Store에서 여러 URL(axios)을 설정하는 가장 좋은 방법은 무엇입니까?

bestcode 2022. 8. 28. 09:40
반응형

Vuex Store에서 여러 URL(axios)을 설정하는 가장 좋은 방법은 무엇입니까?

취득하고 싶은 페이지가 몇 개 있어 정상적으로 동작하고 있습니다만, 데이터량이 적은 반면 페이지 로딩이 조금 늦어지는 것을 알 수 있습니다.

vuex 스토어에서 API를 악시스로 설정하여 성능을 향상시키려면 어떻게 해야 합니까?

스토어:

export default {
    state: { 
    homepage: [],
    aboutUs: []
},


actions: {
  async loadPosts({ commit }) {
    // Define urls pages
    const urlHomepage = 'https://api.domain.com/homepage';
    const urlaboutUs = 'https://api.domain.com/aboutUs';

    // Responses pages
    const responseHomepage = await this.$axios.get(urlHomepage);
    const responseaboutUs = await this.$axios.get(urlaboutUs);

    // variables pages
    this.homepage = responseHomepage.data
    this.aboutUs = responseaboutUs.data

    // mutations pages
    commit('SET_HOMEPAGE', this.homepage)
    commit('SET_aboutUs', this.aboutUs)
  }
},

mutations: {
  SET_HOMEPAGE (state, homepage) {
    state.homepage = homepage;
  },
  SET_aboutUs (state, aboutUs) {
    state.aboutUs = aboutUs;
  }
}
};

제 페이지에는 이렇게 쓰고 있어요.

import {mapState} from 'vuex';

export default {
  name: 'Home',
  mounted() {
    this.$store.dispatch('loadPosts')
  },
  computed: {
    ...mapState([
      'homepage'
    ])
  }
}

추가:

{{homepage}}

API URL을 여러 개 저장할 수 있는 더 좋은 방법이 있나요?Nuxt.js를 사용하고 있습니다.

비동기 콜을 다른 콜이 종료된 후에만 실행하는 것이 아니라 동시에 실행함으로써(특히 2페이지 이상), 처리 속도를 크게 높일 수 있습니다.

버전 1

// Execute async immediately and store the promises
const pH = this.$axios.get(urlHomepage); 
const pA = this.$axios.get(urlaboutUs);

// Await them all at once instead of individually
const [rH, rA] = await Promise.all([pH, pA]);

또는 다른 방법으로 다음과 같이 쓸 수 있습니다.

버전 2

const [rH, rA] = await Promise.all([
  this.$axios.get(urlHomepage),
  this.$axios.get(urlaboutUs)
]);

결과 배열 순서는 호출된 순서와 동일합니다.

그런 다음 결과를 저장합니다.

// variables pages
this.homepage = rH.data
this.aboutUs = rA.data

// mutations pages
commit('SET_HOMEPAGE', this.homepage)
commit('SET_aboutUs', this.aboutUs)

언급URL : https://stackoverflow.com/questions/61297490/what-is-the-best-way-to-set-up-multiple-urls-axios-in-vuex-store

반응형