dsp_099
dsp_099

Reputation: 6121

How much of this business logic belongs in Vuex?

I have a simple app which pulls products from an API and displays them on-page, like this:

enter image description here

I've added Vuex to the app so that the search results as well as the product search array doesn't disappear when the router moves the user to a specific product page.

The search itself consists of the following steps:

You get the idea.

With all of the variables stored in Vuex, it stands to reason all of the business logic should belong there as well, but should it really?

I'm talking specifically about accessing store params such as productsExhausted (when there are no more products to display) or productPage (which increments every time the infinite scroller module is triggered) etc.

How much logic - and what kind - belongs in Vuex? How much does not?

I was under the impression that Vuex is used for storage only but since all of the data is located there, fetching it all back to the Vue app only to send it all back seems like an overly verbose way to address the problem.

Upvotes: 15

Views: 5146

Answers (1)

Doctor
Doctor

Reputation: 7996

Vuex allows you to share data !

For everything that concerns the state of the app its pretty straightforward.

All the data that can be used by multiple components should be added to the store.

Now concerning the business logic, even though I find its not really clear in the official documentation, it should follow the same principle.

What I mean is that logic that can be used by multiple components should be stored in actions. Moreover actions allows you to deal with async operations. Knowing this, your code that pulls the data should definitely be stored in vuex's actions.

What I think you should do is to put the request inside an action, then mutate the state of your variables and automatically your UI will reflect the changes.

Moreover, a good pattern to apply is to convert most of the logic to a state logic. For instance consider this demo of a jumping snowman. In here the click action results on updating a value from the store. Although the interesting part is that one component uses the watch functionnality to be notified when the store changes. This way we keep the logic inside the component but use the store as an event emitter.

var store = new Vuex.Store({
    state: {
    isJumping: 0
  },
  mutations: {
    jump: function(state){
      state.isJumping++;
    }
  }
})


Vue.component('snowman', {
  template: '<div id="snowman" :class="color">⛄</div>',
  computed: {
    isJumping: function(){
      return this.$store.state.isJumping;
    }
  },
  watch: {
    isJumping: function(){
      var tl = new TimelineMax();
      tl.set(this.$el,{'top':'100px'})
      tl.to(this.$el, 0.2, {'top':'50px'});
      tl.to(this.$el, 0.5, {'top':'100px', ease: Bounce.easeOut});
    }
  }
})

Upvotes: 13

Related Questions