5

I understand what the store is and the purpose of Vuex, but now I'm thinking:

"What do I actually put in the store?"

The SPA I'm building handles a lot of data. Initially I was only putting in the "main" stuff. However, is that wrong? Should the store actually hold all data for the SPA? If I present data on the webpage, should that be flowing through the store?

Saurabh
  • 71,488
  • 40
  • 181
  • 244
Garfonzo
  • 3,876
  • 6
  • 43
  • 78

1 Answers1

7

As a rule of thumb, is the data is only used by one of the component, or it is one way propagated to child, you should be okay with having that at component level.

But if data is changed and accessed by more than two components it can be put in centralised state: that is vuex.

Quoting 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. There's a good quote from Dan Abramov, the author of Redux:

Flux libraries are like glasses: you’ll know when you need them.

You can also refer vue-hackernews example, where you can see lists, users are in vuex store, while components also have data while are specific to only that component.

data in component:

  data () {
    const data = {
      loading: false,
      transition: 'slide-up',
      displayedPage: isInitialRender ? Number(this.$store.state.route.params.page) || 1 : -1,
      displayedItems: isInitialRender ? this.$store.getters.activeItems : []
    }
    isInitialRender = false
    return data
  },

state in vuex:

  state: {
    activeType: null,
    itemsPerPage: 20,
    items: {/* [id: number]: Item */},
    users: {/* [id: string]: User */},
    lists: {
      top: [/* number */],
      new: [],
      show: [],
      ask: [],
      job: []
    }
  },
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • 1
    "if data is changed and accessed by more than two components it can be put in centralised state" <-- That's probably a good way to think about it. 2 or more components --> it's going in the store. – Garfonzo Apr 17 '17 at 14:37