Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a Vuex array?

I have a Vuex array (this.buildings). I can't mutate it directly before turning it into a payload for an api, so I tried to clone it with slice():

const buildingsPayload = this.buildings.slice() 
  buildingsPayload.forEach((building, index) => {
  building.index = index
})

However I'm still getting the Do not mutate vuex store state outside mutation handlers. error.

What's the correct way of doing this?

like image 386
alex Avatar asked Jun 30 '17 03:06

alex


1 Answers

Try something like this:

const buildingsPayload = this.buildings.map((b, idx) => Object.assign({ index: idx }, b));

It will also copy the objects, so you're not modifying the state of those.

like image 173
Evan Trimboli Avatar answered Oct 23 '22 02:10

Evan Trimboli