What is the best way to update the entire observed array and trigger a rerender in vue.js without having to iterate an push all the items?
I have read the documentation here: https://vuejs.org/v2/guide/list.html#Replacing-an-Array
But it doesn't make sense to me having to filter, concat or slice just to update the array? There must be something I missed?
I ran into this as well, and a lot of sample code out there from Vue 1.0 gives incorrect information on this topic. So I thought it might be helpful to post my findings in followup to Janspeed's correct answer on this topic.
For example, given an array defined in the
data:
block as follows:To set the entire array (in these examples, to the a local array
var localEvents
), these both work just fine, and you have a bit more flexibility with the second method:You will see samples like this in tutorials, it doesn't work:
It will result in this error:
Per: https://vuejs.org/v2/guide/migration.html#Array-prototype-set-removed
However,
Vue.set
can be used to reactively add elements to an array. Therefore, given an array with length 3:Of course, per the examples in the documentation, if you specify an index value corresponding to a existing array element, it will be replaced by your input object (
newEvent
in the examples above).See: https://vuejs.org/v2/guide/list.html#Replacing-an-Array
i just use
read about it here
As suggested I will repond to this myself to help anyone in the same predicament.
should still work (thank you choasia. Even though it is somewhat unclear in the vue.js documentation. Replacing the entire array will not fall under the caveats mentioned there (thank you Roy J ).
One option might also be to to empty the array and then push the new one like:
Thank you reiner