Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex best practices for complex objects

Tags:

vuex

My Vuex store contains objects with a variety of complexity. Some have nested objects, some have arrays of nest objects.

I could create generic function to mutate a specified property along the lines of:

setProperty(state,{ type, id, prop, value })
{
  state[type][id][prop] = value;
}

but that will quickly get complicated for nested object, arrays of objects. It also seems very tedious to have to create a mutation for every single object property, nested or otherwise.

What are the best practices for creating mutations to modify objects, nested objects, arrays, etc?

Another related issue, is it considered bad form to pass the objects into the mutations as opposed to looking them up in the state:

setProperty(state,{ obj, prop, value })
{
  obj[prop] = value;
}
like image 872
Hilo Avatar asked Apr 24 '17 19:04

Hilo


1 Answers

Generally speaking, it is best if you just could avoid nested state structure at first place. I'm not sure how your data are structured, but if you're doing that because you have relationship between those object or area of object, it might be worth trying normalizing the state shape.

Here is the good article from Redux author. It's talking about Redux but the core concept is very same for the Vuex. https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

And the Vues ORM is a library that do that for you automatically.

like image 76
Kia Ishii Avatar answered Oct 24 '22 11:10

Kia Ishii