Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuex is state.array.push reactive?

Im a bit new to JS and vue and am not quite sure if i understood the documentation correctly. it says:

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), 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.

does this include normal arrays as well, or do elements in arrays not count as "properties" in javascript? I wish to do state.array.push(data) to an array. Is this the correct way to do it?

like image 512
fogx Avatar asked Jul 05 '19 07:07

fogx


2 Answers

Regarding the docs:

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
  2. When you modify the length of the array, e.g. vm.items.length = newLength

Vue will keep reactivity (Array change detection) when using:

  1. push()
  2. pop()
  3. shift()
  4. unshift()
  5. splice()
  6. sort()
  7. reverse()

So the answer to the question is state.array.push reactive ? is Yes

like image 61
Roland Avatar answered Sep 19 '22 15:09

Roland


state.array.push(data) is correct.

What the documentation says is:

// If initially you have an object like this
state = {
   obj:{
       key1: ["dummy"]
    }
};
// this will be reactive
state.obj.key1.push("dummy2");

// however if you add a new property to the object like this,
// then whatever you do with obj['key2'] will not be reactive
state.obj['key2'] = ["dummy"];
like image 44
Dan Lee Avatar answered Sep 21 '22 15:09

Dan Lee