Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating a reactive array in the Vuex's state

Tags:

vue.js

vuejs2

My component would like to add a new reactive-array field to the SST (vuex). I tried in beforeCreate hook, but the added array is not reactive; it's just a plain JS array.

Note that this is not the same as adding/removing elements from an existing array created at the Vue's initialization time. Such arrays are "wrapped" and become reactive as expected, mindful of "Array Change Detection" gotchas.

In my case, I'm trying to dynamically add an entirely new field of array type to the SST and make it reactive at the same time. Possible?

like image 910
Slawomir Avatar asked Feb 23 '18 14:02

Slawomir


People also ask

Is VUEX state reactive?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

Is Vue reactive programming?

One of Vue's most distinctive features is the unobtrusive reactivity system. Component state consists of reactive JavaScript objects. When you modify them, the view updates. It makes state management simple and intuitive, but it's also important to understand how it works to avoid some common gotchas.

What is reactive in Vue JS?

Reactivity is the ability for a variable (array, string, number, object, etc) to update when its value or any other variable that it makes reference to is changed after declaration.


1 Answers

Have a look at Reactivity in Depth - Change Detection Caveats:

Change Detection Caveats

Due to the limitations of modern JavaScript, Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

But you say you are adding an array dynamically:

I'm trying to dynamically add an entirely new field of array type to the SST and make it reactive at the same time. Possible?

From the docs (bold is mine):

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method:

Vue.set(vm.someObject, 'myArrayName', [1,2,3]);

Which should help you making your array reactive.

like image 53
acdcjunior Avatar answered Sep 21 '22 15:09

acdcjunior