1
votes

Expected to achieve: Most correct way to modify specific record stored in the Vuex state with one big (batch) write

Context: Vuex state contains list of records with default values for each record.

Logic Component initialises and uses getter to get one of the records. It's needed to add new properties to the record and overwrite existing values.

Question Is it acceptable to modify the object returned by the Vuex getter and later commit the whole result into the state? And if yes, what would be the best approach considering it will have to overwrite existing record in Vuex.

P.S: I also wonder if it can result in breaking behaviour of other components that are "getting" the same record that will be overwritten, and will appreciate a lot your thoughts on this topic :-)

2

2 Answers

2
votes

Don't modify Vuex data except via Vuex mutation

1) First, clone the getter record. Make sure you deep clone if your record has anything but primitive properties, i.e it has properties that are objects or functions. Here are some cloning options, notice that many don't correctly deep clone.

2) Once you're done mutating the clone, call a Vuex action and have that action call a mutation. It's good practice to only call mutations from actions.

3) In that mutation, use Vue.set (or splice) to replace the state record.

4) Yes, if you mutated the getter directly, it would be mutated anywhere else it was used.

1
votes

See Change detection caveats in the VueJS reactivity guide.

Sometimes you may want to assign a number of properties to an existing object, for example using Object.assign() or _.extend(). However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:

// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })