Vuex setting state issue with array?

Encountered a weird issue storing a value in an array in the store. I wrote a quick example, two text fields “all” and “somevalue” who’s values display from a computed call (10/55). I also added some console logging to watch what is going on.

Press “click” and I display the current state of the first element of the state array adata[0] which is 10 and the entire array using getters (shows [10,20,30]) as expected and the value of singlevalue @ 55.

I then commit 44 to adata[0] and 88 to ‘somevalue’. The second text box reflects the second commit as it changes to 88 while the first text box remains at 10. Click “after” and in the console you see the second dump of data only now, adata[0] still shows 10 while the array dump shows [44,20,30].

adata[0] and adata no longer match.

What am I doing wrong in setting this value??


this will resolve your issue’t-the-DOM-updating

It’s not that the DOM doesn’t update - adata, the array[] shows “10,20,30” and “44,20,30” after the mutation. The getter for the array returns “44,20,30” while “array[0]” returns 10, the first value. Why when I change array[0] to 44, the getter of array[0] returns 10?


You need to change this line in your setters. Arrays in vue is a bit special and just setting a value of a index doesn’t trigger reactivity. You can however use Vue.set instead and it will work:

first (state, v) { Vue.set(state.adata, 0, v) },

See here:

vue doesn’t pick changes when you directly mutate an array with the index, instead use array.splice or Vue.set

An hour of checking examples and I didn’t find that caveat page anywhere. That did the job.

1 Like