How do I clone a Vuex array?

I have a Vuex ( this.buildings

) array . I cannot mutate it directly before turning it into a payload for the api, so I tried to clone it with slice()

:

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

      

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

.

What is the correct way to do this?

+3


source to share


1 answer


Try something like this:

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

      



It will copy objects as well, so you don't change their state.

+3


source







All Articles