programing

Vuex에서 (객체의 소품이 아닌) 단일 계산 소품으로 모듈 상태 소품을 가져오는 방법은?

itmemos 2023. 7. 1. 08:03
반응형

Vuex에서 (객체의 소품이 아닌) 단일 계산 소품으로 모듈 상태 소품을 가져오는 방법은?

단일 모듈 상태:

   const charactersModule = {
      state: () => ({
        characters: [],
        isLoading: false,
        totalPages: 0,
        currentPage: 1,
        itemsPerPage: ITEMS_PER_PAGE,
      }),
      getters: {},
      mutations: {},
      actions: {
        async getCharacters({state}, page = state.currentPage) {
          try {
            state.isLoading = true;
            const res = await fetch(`${BASE_URL}character/?page=${page}`);
    
            if (res.ok) {
              const { info, results } = await res.json();
    
              state.characters = results;
            }
          } catch (e) {
            console.log(e);
          } finally {
            state.isLoading = false;
          }
        },
      },
    };
    
    export default createStore({
      modules: {
        characters: charactersModule,
      },
    });

SFC의 경우:

// some component
    ...
      methods: {
        ...mapActions(['getCharacters']),
        }
    
      computed: {
        ...mapState(['characters'])
      },
    
      mounted() {
        this.getCharacters()
      },

이 SFC 내에서 문자, isLoading, totalPapages, currentPage itemsPerPage와 같은 계산된 속성에 액세스할 수 있을 것으로 예상됩니다....mapState(['characters'])에서 얻을 수 있는 것은 이 모든 속성이 포함된 개체이지만, 개체의 일부가 아닌 단일 계산된 속성으로 가져와야 합니다.어떻게 해야 하나요?

사용해 보십시오.createNamespacedHelpers 모듈 이름으로 접두사를 붙여 상태를 확인할 수 있습니다.

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('characters')

 ...
      methods: {
        ...mapActions(['getCharacters']),
        }
    
      computed: {
        ...mapState(['characters'])
      },
    
      mounted() {
        this.getCharacters()
      },

언급URL : https://stackoverflow.com/questions/72583138/how-to-get-module-state-props-as-single-computed-props-not-as-props-of-an-objec

반응형