Skip to content
Advertisement

Mutate Vuex array passed in the payload

What’s the technical difference between next two approaches? Example is trivial but when I have huge nested objects, I need to pass lots of IDs in order to find desired object inside the mutation.

In second example I pass an array and just mutate it. Again, technically in both examples we invoke the same push method. Am I right? Should be the same.

const state = () => ({
  cards: []
});

mutations: {
  addCard(state, card) {
    state.cards.push(card)
  }
}

// Component...

this.$store.commit('addCard', {...card});

and

const state = () => ({
  cards: []
});

mutations: {
  addCard(state, data) {
    data.cards.push(data.card)
  }
}

// Component...

this.$store.commit('addCard', { cards: this.$store.cards, card: {...card} }); 

Advertisement

Answer

What’s the technical difference… ?

I know you’re not asking what the literal difference is between the two, but I’ll just make that clear first.

  • In the first snippet, you’re passing a new item and adding it to an array state that you access through the mutation’s state argument.
  • In the second snippet, you pass both the array state and the item, and access the array through the payload instead.

Again, technically in both examples we invoke same push method. Am I right?

Yes, these two accomplish the exact same result. The array state, whether accessed through the mutation argument or through the payload are the exact same object (i.e. ===).

The pattern in the second snippet can be very useful when mutating deeply nested state, like you found. The drawback is that it might not be quite clear what’s being mutated, to someone who tries to learn your code later.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement