joeforker
joeforker

Reputation: 41747

Will vuex work properly with generic mutations that don't reference `state`?

I’m using vuex with a tree of data. It's reactive and works well because we have a corresponding tree of components. Since the structure is a tree, it’s common to want to mutate a deeply nested child object. The easy way to implement that is with a mutation that accepts the child in its payload:

removeLeaf(state, { child, leaf }) {
  child.children = child.children.filter((i: any) => i !== leaf);
  state = state; // silence warning
},

A different way would be to change the mutation to work like this:

removeLeaf(state, { child_, leaf }) {
  let child = searchForChild(state, child_);
  child.children = child.children.filter((i: any) => i !== leaf);
},

I’m happy with the first way. Are there any drawbacks to writing mutations that modify a child object of state by using payload instead of the state parameter?

Upvotes: 1

Views: 204

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20855

I don't think it'll work properly.

Vue's and Vuex's reactivity system is based on Javascript Getter and Setter.

If you console.log the state in any mutation, you will see something like this:

enter image description here

The get and set is the getter and setter of your Vuex States.

Without the setter, Vue's reactivity system likely wouldn't work.

Try console.log state and child in your mutation. You will likely see that the child doesn't contain setter.

If the setter is not there, Vue wouldn't know that you have updated the state of child, and you will likely have reactivity problem.

Upvotes: 1

Related Questions