Home » vue » using generic vuex mutations [closed]

using generic vuex mutations [closed]

Posted by: admin November 26, 2021 Leave a comment


I have been working in vue/vuex for about a year. In my apps, find myself eventually adding a couple of mutators in my store(s) like so

mutations: {
setAny(state, obj){
  Object.keys(obj).forEach(k => state[k] = obj[k]);
toggleAny(state, key){//booleans
  state[key] = !state[key];

Then I can quickly get objects or multiple objects in the state with patterns like this:

  myAsyncThing:({commit}) => {
    asyncThing.then(results => {
      const foo = specialSauceA(results);
      const bar = specialSauceB(foo);
      const baz = specialSauceC(bar);
      commit('setAny', {foo, bar, baz});//slick one liner!

I prefer this over writing a mutator for every shared state key I might update. Of course, I also write plenty of custom mutators, but I have been leaning towards this approach when I need to add props to the state that need to be reliably reactive and set from an action or component.

The reason I ask is mostly I wonder why I have never seen any vuex code examples that do this and I wonder why not? When I first did this, I felt naughty, but over time, this pattern has been a huge time saver with no real side effects.

So is there a flaw with this approach given the discussion surrounding breaking state mutations out of actions and into mutations?


I thing your approach is ok. Because so much double code with mutations some times. If you will see Vuex 4.x in https://github.com/vuejs/roadmap it has

Getting rid of the need for separating actions and mutations

that mean what you are a step ahead