Search code examples
javascriptvue.jsvuejs2vuex

Vue.js SPA project structure - where to use Vuex store and call APIs


I have the following project structure in my Vue app:

components/
    article/
        AppList.vue
    common/
        AppObserver.vue
        NoSSR.vue
    layout/
        AppFooter.vue
        AppHeader.vue                
    ui/
        AppButton.vue
        AppList.vue
pages/
    ArticlePage/
        index.vue
        ArticleTitle.vue
        LastArticlesSection.vue
    UserPage.vue
        ....

Is it a good practice to use the Vuex store and call APIs only from the index.vue file of the pages? And then to pass every necessary data to the children from them via props?

Or should I use the store and APIs in other components too, for example in AppList.vue (which is a common component used across several pages).


Solution

  • One of the purposes of Vuex is to decouple unrelated components, so it intends to be used directly from any component that should access global data that goes beyond the scope of the parent. Some proof of this is in the existence of the helper methods such as mapState which would have no purpose otherwise. For components that are tightly related to the parent, it often makes more sense to use props instead.

    There is often a use for importing APIs into Vuex as well, and this is ok.

    Vuex is good for:

    • Data that is shared by multiple components
    • A centralized API (so that you can access it from multiple components)

    Vuex is not as good for:

    • If props are simpler and get the job done easily, there may be no reason to use Vuex.
    • Situations where persistent data is not a concern

    From the docs

    if you are building a medium-to-large-scale SPA, chances are you have run into situations that make you think about how to better handle state outside of your Vue components, and Vuex will be the natural next step for you.