Home > Software design >  How to get module state props as single computed props (not as props of an object) from Vuex?
How to get module state props as single computed props (not as props of an object) from Vuex?

Time:06-11

I have a state with single module:

   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,
      },
    });

Then in SFC:

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

I expect that inside this SFC I can access computed properties: characters, isLoading, totalPapges, currentPage and itemsPerPage. What I actually get from ...mapState(['characters']) is an object with all this props, but I need to get them as single computed props (not as part of an object). How can I do this?

CodePudding user response:

Try to use createNamespacedHelpers help to get your state with prefixing them by the module name:

import { createNamespacedHelpers } from 'vuex'

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

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